33

My understanding is that enum is like union in C and the system will allocate the largest of the data types in the enum.

enum E1 {
    DblVal1(f64),
}

enum E2 {
    DblVal1(f64),
    DblVal2(f64),
    DblVal3(f64),
    DblVal4(f64),
}

fn main() {
    println!("Size is {}", std::mem::size_of::<E1>());
    println!("Size is {}", std::mem::size_of::<E2>());
}

Why does E1 takes up 8 bytes as expected, but E2 takes up 16 bytes?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
RajV
  • 6,860
  • 8
  • 44
  • 62

2 Answers2

37

In Rust, unlike in C, enums are tagged unions. That is, the enum knows which value it holds. So 8 bytes wouldn't be enough because there would be no room for the tag.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
30

As a first approximation, you can assume that an enum is the size of the maximum of its variants plus a discriminant value to know which variant it is, rounded up to be efficiently aligned. The alignment depends on the platform.

This isn't always true; some types are "clever" and pack a bit tighter, such as Option<&T>. Your E1 is another example; it doesn't need a discriminant because there's only one possible value.

The actual memory layout of an enum is undefined and is up to the whim of the compiler. If you have an enum with variants that have no values, you can use a repr attribute to specify the total size.

You can also use a union in Rust. These do not have a tag/discriminant value and are the size of the largest variant (perhaps adding alignment as well). In exchange, these are unsafe to read as you can't be statically sure what variant it is.

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366