Skip to content

Commit 473fd02

Browse files
authored
Update sizes.md (#228)
Adding more details in how to control Rust enum size and discriminant values.
1 parent 8dd749d commit 473fd02

File tree

1 file changed

+9
-0
lines changed

1 file changed

+9
-0
lines changed

src/enums/sizes.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,16 @@ enum Foo {
1717
B,
1818
}
1919
20+
#[repr(u32)]
21+
enum Bar {
22+
A, // 0
23+
B = 10000,
24+
C, // 10001
25+
}
26+
2027
fn main() {
2128
dbg_size!(Foo);
29+
dbg_size!(Bar);
2230
dbg_size!(bool);
2331
dbg_size!(Option<bool>);
2432
dbg_size!(&i32);
@@ -32,6 +40,7 @@ fn main() {
3240

3341
Key Points:
3442
* Internally Rust is using a field (discriminant) to keep track of the enum variant.
43+
* `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.
3544
* As a niche optimization an enum discriminant is merged with the pointer so that `Option<&Foo>` is the same size as `&Foo`.
3645
* `Option<bool>` is another example of tight packing.
3746
* For [some types](https://doc.rust-lang.org/std/option/#representation), Rust guarantees that `size_of::<T>()` equals `size_of::<Option<T>>()`.

0 commit comments

Comments
 (0)