Why is the size of `char` 4 bytes in Rust?
此代码显示
1 | println!("char : {}", std::mem::size_of::<char>()); |
在https://play.rust-lang.org/我也得到4个字节
首先:Rust中的
1 2 3 4 | fn main() { let c: char ="??".chars().next().unwrap(); println!("?? is {} ({})", c, c as u32); } |
在围栏上。
话虽如此,Rust
注意:标量值的重点在于,许多"字符"实际上是由Unicode中多个组合字符组成的字素,在这种情况下,需要多个
没什么特别的。四个字节只是两个字节的最小乘方,您可以在其中存储任何Unicode标量值。其他各种语言也做同样的事情。
Char是四个字节,它不依赖于体系结构。
为什么?根据UTF-8维基百科的文章。
The first 128 characters (US-ASCII) need one byte. The next 1,920
characters need two bytes to encode. Three bytes are needed for
characters in the rest of the Basic Multilingual Plane, which contains
virtually all characters in common use. Four bytes are needed for
characters in the other planes of Unicode.
因此,如果要表示任何可能的Unicode字符,则编译器必须保存4个字节。
您还应该考虑字节对齐:http://www.eventhelix.com/realtimemantra/ByteAlignmentAndOrdering.htm