On Rust Playground, the size of an Option<bool>
is 1. Is rust packing the option information into the bool itself? So the Option represents the 3 possible states: None
, Some(false)
, Some(true)
?
use std::mem::size_of;
fn main() {
println!("{}", size_of::<Option<bool>>()); // 1
}
Yes. This is called niche optimization. bool
has a niche of 7 bits (7 unused bits), and we pack Option::None
into those.
You can inspect the bytes (playground):
fn main() {
fn print_bytes(v: Option<bool>) {
println!("{:08b}", unsafe { std::mem::transmute::<Option<bool>, u8>(v) });
}
print_bytes(Some(false));
print_bytes(Some(true));
print_bytes(None);
}
00000000
00000001
00000010
You can see we use the second bit to indicate None
.
Note that as said in the comment by @Cerberus, the memory layout is not guaranteed for #[repr(rust)]
types and one should not rely on it.