mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-03-22 06:51:58 +02:00
Update sizes.md (#228)
Adding more details in how to control Rust enum size and discriminant values.
This commit is contained in:
parent
8dd749da60
commit
473fd02be7
@ -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<bool>);
|
||||
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<bool>` is another example of tight packing.
|
||||
* For [some types](https://doc.rust-lang.org/std/option/#representation), Rust guarantees that `size_of::<T>()` equals `size_of::<Option<T>>()`.
|
||||
|
Loading…
x
Reference in New Issue
Block a user