英文:
How does niche optimization for an enum work in Rust?
问题
Using Option<bool>
作为示例,我理解Option<bool>
和bool
的大小都是1字节,但我仍然不完全确定其变体的内存分配是如何发生的。
它是否工作如下?
Some(true)
变成 00000001
Some(false)
变成 00000000
None
变成除了 00000001
或 00000000
之外的某些值(例如:00000010
)
英文:
Using Option<bool>
as an example, I get that the sizes of Option<bool>
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<bool>
的所有3个可能值的字节值:
fn main() {
let a:[Option<bool>;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。
请注意,这不是官方规定的行为,所以在将来的版本中可能会更改。不要依赖这种行为。
英文:
This code will print the byte values of all 3 possible values for Option<bool>
:
fn main() {
let a:[Option<bool>;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:?}");
}
}
Output:
Some(true) 1
Some(false) 0
None 2
Seems like None
is represented as 2.
Note this isn't officially specified so it may change in future versions. Do not rely on this behavior.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论