为什么在Rust中`char`的大小为4个字节?

Why is the size of `char` 4 bytes in Rust?

此代码显示char占用4个字节:

1
println!("char : {}", std::mem::size_of::<char>());
  • 为什么要占用4个字节?
  • 大小取决于平台,还是总是4个字节?
  • 如果始终为4个字节,这是否有特殊用途?
  • 编译器是否保证char的某个最小大小?
  • 在https://play.rust-lang.org/我也得到4个字节


    首先:Rust中的char是表示Unicode标量值的唯一整数值??。例如,考虑?? (又称Poo堆,也就是U + 1F4A9),在Rust中,它将用char表示,其值为十进制的128169(即十六进制的0x1F4A9):

    1
    2
    3
    4
    fn main() {
        let c: char ="??".chars().next().unwrap();
        println!("?? is {} ({})", c, c as u32);
    }

    在围栏上。

    话虽如此,Rust char是4个字节,因为4个字节是2个字节的最小乘方,它可以保存任何Unicode标量值的整数值。决定是由领域驱动的,而不是架构约束。

    注意:标量值的重点在于,许多"字符"实际上是由Unicode中多个组合字符组成的字素,在这种情况下,需要多个char


    char是四个字节。它始终是四个字节,它将始终是四个字节。它是四个字节,剩下四个字节。

    没什么特别的。四个字节只是两个字节的最小乘方,您可以在其中存储任何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