作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
考虑这个愚蠢的枚举:
enum Number {
Rational {
numerator: i32,
denominator: std::num::NonZeroU32,
},
FixedPoint {
whole: i16,
fractional: u16,
},
}
Rational变体中的数据占8个字节,FixedPoint变体中的数据占4个字节。 Rational 变体有一个必须为非零的字段,所以我希望枚举布局规则将其用作鉴别器,零表示存在 FixedPoint 变体。
但是,这:
fn main() {
println!("Number = {}", std::mem::size_of::<Number>(),);
}
打印:
Number = 12
因此,枚举为显式鉴别器获取空间,而不是利用非零字段的存在。
为什么编译器不能使这个枚举更小?
最佳答案
尽管像 Option<&T>
这样的简单情况can be handled without reserving space for the tag , rustc 中的布局计算器仍然不够聪明,无法优化具有多个非空变体的枚举的大小。
这是 issue #46213在 GitHub 上。
你问的情况很明确,但也有类似的情况,枚举看起来应该优化,但实际上不可能,因为优化会排除采用内部引用;例如,参见 Why does Rust use two bytes to represent this enum when only one is necessary?
关于enums - 为什么这个 Rust 枚举没有变小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57326734/
我是一名优秀的程序员,十分优秀!