diff --git a/src/enums/sizes.md b/src/enums/sizes.md index 5736914d..c7fd3683 100644 --- a/src/enums/sizes.md +++ b/src/enums/sizes.md @@ -17,8 +17,16 @@ enum Foo { B, } +#[repr(u32)] +enum Bar { + A, // 0 + B = 10000, + C, // 10001 +} + fn main() { dbg_size!(Foo); + dbg_size!(Bar); dbg_size!(bool); dbg_size!(Option); dbg_size!(&i32); @@ -32,6 +40,7 @@ fn main() { Key Points: * Internally Rust is using a field (discriminant) to keep track of the enum variant. + * `Bar` enum demonstrates that there is a way to control the discriminant value and type. If `repr` is removed, the discriminant type takes 2 bytes, becuase 10001 fits 2 bytes. * As a niche optimization an enum discriminant is merged with the pointer so that `Option<&Foo>` is the same size as `&Foo`. * `Option` is another example of tight packing. * For [some types](https://doc.rust-lang.org/std/option/#representation), Rust guarantees that `size_of::()` equals `size_of::>()`.