枚举在Rust中的特定领域优化是如何工作的?

huangapple go评论63阅读模式
英文:

How does niche optimization for an enum work in Rust?

问题

Using Option<bool>作为示例,我理解Option<bool>bool的大小都是1字节,但我仍然不完全确定其变体的内存分配是如何发生的。

它是否工作如下?

Some(true) 变成 00000001

Some(false) 变成 00000000

None 变成除了 0000000100000000 之外的某些值(例如:00000010

英文:

Using Option&lt;bool&gt; as an example, I get that the sizes of Option&lt;bool&gt; and bool are both 1 byte, but I'm still not 100% about how the memory allocation of its variants occur.

Does it work like the following?

Some(true) to 00000001

Some(false) to 00000000

None something (changed from "anything" as per below comments) other than 00000001 or 00000000 (ex: 00000010)

答案1

得分: 5

这段代码将打印出Option&lt;bool&gt;的所有3个可能值的字节值:

fn main() {
    let a:[Option&lt;bool&gt;;3]=[Some(true), Some(false), None];
    
    for i in a {
        // Re-Interpret the bytes of the option as a number
        let j:u8 = unsafe { std::mem::transmute(i) };
        println!("{i:?} {j:?}");
    }
}

输出结果:

Some(true) 1
Some(false) 0
None 2

似乎None 被表示为 2。

Playground链接

请注意,这不是官方规定的行为,所以在将来的版本中可能会更改。不要依赖这种行为。

英文:

This code will print the byte values of all 3 possible values for Option&lt;bool&gt;:

fn main() {
    let a:[Option&lt;bool&gt;;3]=[Some(true), Some(false), None];
    
    for i in a {
        // Re-Interpret the bytes of the option as a number
        let j:u8 = unsafe { std::mem::transmute(i) };
        println!(&quot;{i:?} {j:?}&quot;);
    }
}

Output:

Some(true) 1
Some(false) 0
None 2

Seems like None is represented as 2.

Playground Link

Note this isn't officially specified so it may change in future versions. Do not rely on this behavior.

huangapple
  • 本文由 发表于 2023年6月8日 15:25:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76429517.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定