Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does niche optimization for an enum work in Rust?

Tags:

enums

rust

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)

like image 759
kenta_desu Avatar asked Oct 16 '25 09:10

kenta_desu


1 Answers

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.

like image 118
mousetail Avatar answered Oct 18 '25 04:10

mousetail