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
)
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.
Playground Link
Note this isn't officially specified so it may change in future versions. Do not rely on this behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With