为什么枚举需要额外的内存大小?(Why does an enum require extra memory size?)

系统教程 行业动态 更新时间:2024-06-14 16:57:39
为什么枚举需要额外的内存大小?(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.

更多推荐

本文发布于:2023-04-13 12:01:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/7e96361ed4c7fe303e8c6dbba66a48bb.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:内存大小   enum   require   size   memory

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!