Adding a field to a struct X can make Option<X> smaller

96 points octo_anders

Consider this:

struct MyStruct {
    x: u64,
    y: u32,
}

struct MyStructWithBool {
    x: u64,
    y: u32,
    z: bool,
}

fn main() {
    println!("Size of Option<MyStruct>: {}", std::mem::size_of::<Option<MyStruct>>()); // Prints 16
    println!("Size of Option<MyStructWithBool>: {}", std::mem::size_of::<Option<MyStructWithBool>>()); // Prints 24
}

Adding the field z of type bool, reduces the size of Option<MyStruct> from 24 to 16.

I guess this is because padding-bytes can't be used for niches, but the bits in a bool can. But I still find it funny.