enums - 为什么这个 Rust 枚举没有变小?

标签 enums rust memory-layout

考虑这个愚蠢的枚举:

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/57711186/

相关文章:

堆栈上的常量数据?

c++ - 具有原始类型的单个数组成员的标准布局结构的保证内存布局

c++ - 在 C++ 中通过 '::' 访问枚举值

asp.net - 枚举和开关盒

java - 使用 enum.values() 与 String 数组时是否会影响性能?

rust - 如何将 Multipart::from_request 与 tiny_http::Request 一起使用?

string - 高效的弦修剪

java - 使用 lombok 创建枚举

rust - 如何在 Rust 中将字符串中的所有字符大写?

c++ - 类型转换内存 union