为什么枚举需要额外的内存大小?(Why does an enum require extra memory size?)
我的理解是enum就像C中的union一样,系统将分配enum中最大的数据类型。
enum E1 { DblVal1(f64), } enum E2 { DblVal1(f64), DblVal2(f64), DblVal3(f64), DblVal4(f64), } fn main() { println!("Size is {}", std::mem::size_of::<E1>()); println!("Size is {}", std::mem::size_of::<E2>()); }为什么E1按预期占用8个字节,但E2占用16个字节?
My understanding is that enum is like union in C and the system will allocate the largest of the data types in the enum.
enum E1 { DblVal1(f64), } enum E2 { DblVal1(f64), DblVal2(f64), DblVal3(f64), DblVal4(f64), } fn main() { println!("Size is {}", std::mem::size_of::<E1>()); println!("Size is {}", std::mem::size_of::<E2>()); }Why does E1 takes up 8 bytes as expected, but E2 takes up 16 bytes?
最满意答案
在Rust中,与C不同, enum被标记为联合 。 也就是说, enum知道它拥有哪个值。 所以8个字节是不够的,因为标签没有空间。
In Rust, unlike in C, enums are tagged unions. That is, the enum knows which value it holds. So 8 bytes wouldn't be enough because there would be no room for the tag.
更多推荐
发布评论