以Option<bool>
为例,我得到Option<bool>
和bool
的大小都是1字节,但我仍然不是Option<bool>
%地了解它的变体的内存分配是如何发生的.
它的工作原理如下吗?
Some(true)
%至00000001
%
Some(false)
%至00000000
%
除了00000001
或00000000
(例如:00000010
)以外的None
个左右(根据下面的 comments ,从"任何"改为"任何")
以Option<bool>
为例,我得到Option<bool>
和bool
的大小都是1字节,但我仍然不是Option<bool>
%地了解它的变体的内存分配是如何发生的.
它的工作原理如下吗?
Some(true)
%至00000001
%
Some(false)
%至00000000
%
除了00000001
或00000000
(例如:00000010
)以外的None
个左右(根据下面的 comments ,从"任何"改为"任何")
此代码将打印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.
注意:这不是官方指定的,因此它可能会在future 的版本中更改.不要依赖这种行为.