You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/enums/sizes.md
+9Lines changed: 9 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -17,8 +17,16 @@ enum Foo {
17
17
B,
18
18
}
19
19
20
+
#[repr(u32)]
21
+
enum Bar {
22
+
A, // 0
23
+
B = 10000,
24
+
C, // 10001
25
+
}
26
+
20
27
fn main() {
21
28
dbg_size!(Foo);
29
+
dbg_size!(Bar);
22
30
dbg_size!(bool);
23
31
dbg_size!(Option<bool>);
24
32
dbg_size!(&i32);
@@ -32,6 +40,7 @@ fn main() {
32
40
33
41
Key Points:
34
42
* 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.
35
44
* As a niche optimization an enum discriminant is merged with the pointer so that `Option<&Foo>` is the same size as `&Foo`.
36
45
*`Option<bool>` is another example of tight packing.
37
46
* 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