Skip to content

Commit acaca9a

Browse files
authored
Merge pull request #1056 from bstrie/66fix
1.66 blog: clarify enum discriminant section
2 parents 427fb4d + ea1ab1b commit acaca9a

File tree

1 file changed

+3
-10
lines changed

1 file changed

+3
-10
lines changed

posts/2022-12-15-Rust-1.66.0.md

+3-10
Original file line numberDiff line numberDiff line change
@@ -51,20 +51,13 @@ enum Bar {
5151
A,
5252
B,
5353
C = 42,
54+
D,
5455
}
5556
```
5657

57-
Here the `Bar` enum is guaranteed to have the same layout as `u8`. Each variant will use either the specified discriminant value or default to starting with 0.
58+
Here the `Bar` enum is guaranteed to have the same layout as `u8`. In addition, the `Bar::C` variant is guaranteed to have a discriminant of 42. Variants without explicitly-specified values will have discriminants that are automatically assigned according to their order in the source code, so `Bar::A` will have a discriminant of 0, `Bar::B` will have a discriminant of 1, and `Bar::D` will have a discriminant of 43. Without this feature, the only way to set the explicit value of `Bar::C` would be to add 41 unnecessary variants before it!
5859

59-
```rust
60-
assert_eq!(0, Bar::A as u8);
61-
assert_eq!(1, Bar::B as u8);
62-
assert_eq!(42, Bar::C as u8);
63-
```
64-
65-
You could even add fields to enums with `#[repr(Int)]`, and they would be laid out in a predictable way. Previously, however, you could not use these features together. That meant that making `Foo::C`'s discriminant equal to 42 as above would be harder to achieve. You would need to add 41 hidden variants in between as a workaround with implicit discriminants!
66-
67-
Starting in Rust 1.66.0, the above example compiles, allowing you to use explicit discriminants on any enum with a `#[repr(Int)]` attribute.
60+
Note: whereas for field-less enums it is possible to inspect a discriminant via `as` casting (e.g. `Bar::C as u8`), Rust provides no language-level way to access the raw discriminant of an enum with fields. Instead, currently unsafe code must be used to inspect the discriminant of an enum with fields. Since this feature is intended for use with cross-language FFI where unsafe code is already necessary, this should hopefully not be too much of an extra burden. In the meantime, if all you need is an opaque handle to the discriminant, please see the `std::mem::discriminant` function.
6861

6962
### `core::hint::black_box`
7063

0 commit comments

Comments
 (0)