]> git.lizzy.rs Git - rust.git/blob - src/docs/default_union_representation.txt
Add iter_kv_map lint
[rust.git] / src / docs / default_union_representation.txt
1 ### What it does
2 Displays a warning when a union is declared with the default representation (without a `#[repr(C)]` attribute).
3
4 ### Why is this bad?
5 Unions in Rust have unspecified layout by default, despite many people thinking that they
6 lay out each field at the start of the union (like C does). That is, there are no guarantees
7 about the offset of the fields for unions with multiple non-ZST fields without an explicitly
8 specified layout. These cases may lead to undefined behavior in unsafe blocks.
9
10 ### Example
11 ```
12 union Foo {
13     a: i32,
14     b: u32,
15 }
16
17 fn main() {
18     let _x: u32 = unsafe {
19         Foo { a: 0_i32 }.b // Undefined behavior: `b` is allowed to be padding
20     };
21 }
22 ```
23 Use instead:
24 ```
25 #[repr(C)]
26 union Foo {
27     a: i32,
28     b: u32,
29 }
30
31 fn main() {
32     let _x: u32 = unsafe {
33         Foo { a: 0_i32 }.b // Now defined behavior, this is just an i32 -> u32 transmute
34     };
35 }
36 ```