gpt4 book ai didi

rust - 为什么我不能将 `u32` 转换为 `char` ?

转载 作者:行者123 更新时间:2023-11-29 07:42:37 34 4
gpt4 key购买 nike

我正在努力学习 Rust,但我一直在思考 char 为什么是 4 字节宽。我可以将 char 转换为 u32 并成功(它们都是 4 字节宽),但是,当我从 u32 转换时对于 char,Rust 提示:

fn main() {
let pizza_hex: u32 = 0x1f355;
let pizza: char = '🍕'; // (pizza char: http://www.fileformat.info/info/unicode/char/1f355/index.htm)

// pizza as hex = 1f355
println!("pizza as hex = {:x}", pizza as u32);

// size of pizza = 4
println!("size of pizza = {}", std::mem::size_of_val(&pizza));

// This doesn't work super well
println!("{} == {}", pizza_hex as char, pizza);
}
error[E0604]: only `u8` can be cast as `char`, not `u32`
--> src/main.rs:12:26
|
12 | println!("{} == {}", pizza_hex as char, pizza);
| ^^^^^^^^^^^^^^^^^

有什么想法吗?

最佳答案

每个 char 都是一个有效的 u32 值,但不是每个 u32 值都是一个有效的 字符

char 的属性持有有效的 Unicode 代码点 factors into memory safety :

Behavior considered undefined

  • Invalid values in primitive types, even in private fields and locals:
    • A value in a char which is a surrogate or above char::MAX.

要在运行时将 u32 转换为 char,试试这个:

if let Some(pizza_from_hex) = std::char::from_u32(pizza_hex) {
println!("{} == {}", pizza_from_hex, pizza);
}

如果您只是不想在字 rune 字中使用令人毛骨悚然的 Unicode 字形,您可以使用 Unicode 转义序列:

let pizza_from_hex = '\u{01f355}';

println!("{} == {}", pizza_from_hex, pizza);

关于rust - 为什么我不能将 `u32` 转换为 `char` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26107876/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com