]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_error_codes/src/error_codes/E0732.md
Rollup merge of #107190 - fmease:fix-81698, r=compiler-errors
[rust.git] / compiler / rustc_error_codes / src / error_codes / E0732.md
1 An `enum` with a discriminant must specify a `#[repr(inttype)]`.
2
3 Erroneous code example:
4
5 ```compile_fail,E0732
6 enum Enum { // error!
7     Unit = 1,
8     Tuple() = 2,
9     Struct{} = 3,
10 }
11 # fn main() {}
12 ```
13
14 A `#[repr(inttype)]` must be provided on an `enum` if it has a non-unit
15 variant with a discriminant, or where there are both unit variants with
16 discriminants and non-unit variants. This restriction ensures that there
17 is a well-defined way to extract a variant's discriminant from a value;
18 for instance:
19
20 ```
21 #[repr(u8)]
22 enum Enum {
23     Unit = 3,
24     Tuple(u16) = 2,
25     Struct {
26         a: u8,
27         b: u16,
28     } = 1,
29 }
30
31 fn discriminant(v : &Enum) -> u8 {
32     unsafe { *(v as *const Enum as *const u8) }
33 }
34
35 fn main() {
36     assert_eq!(3, discriminant(&Enum::Unit));
37     assert_eq!(2, discriminant(&Enum::Tuple(5)));
38     assert_eq!(1, discriminant(&Enum::Struct{a: 7, b: 11}));
39 }
40 ```