File tree Expand file tree Collapse file tree 2 files changed +10
-8
lines changed Expand file tree Collapse file tree 2 files changed +10
-8
lines changed Original file line number Diff line number Diff line change @@ -40,10 +40,12 @@ let f = u.f1;
40
40
Unions have no notion of an "active field". Instead, every union access just
41
41
interprets the storage at the type of the field used for the access. Reading a
42
42
union field is equivalent to a [ ` transmute ` ] : The data in the union, no matter
43
- how it was stored there, is transmuted to the type of the field. Reading data
44
- at a bad type results in undefined behavior (for example, reading the value ` 3 `
45
- at type ` bool ` ). For this reason, all reads of union fields have to be placed
46
- in ` unsafe ` blocks:
43
+ how it was stored there, is transmuted to the type of the field. Just like with
44
+ any other transmute, it is the programmer's responsibility to make sure that the
45
+ data is valid for the field type. Failing to do so results in undefined
46
+ behavior (for example, reading the value ` 3 ` at type ` bool ` is undefined
47
+ behavior). For this reason, all reads of union fields have to be placed in
48
+ ` unsafe ` blocks:
47
49
48
50
``` rust
49
51
# union MyUnion { f1 : u32 , f2 : f32 }
Original file line number Diff line number Diff line change 3
3
A * union type* is a nominal, heterogeneous C-like union, denoted by the name of
4
4
a [ ` union ` item] .
5
5
6
- A union contains the value of any one of its fields. Since the accessing the
7
- wrong field can cause unexpected or undefined behaviour, ` unsafe ` is required
8
- to read from a union field or to write to a field that doesn't implement
9
- [ ` Copy ` ] .
6
+ A union access transmutes the content of the union to the type of the accessed
7
+ field. Since transmutes can cause unexpected or undefined behaviour, ` unsafe ` is
8
+ required to read from a union field or to write to a field that doesn't
9
+ implement [ ` Copy ` ] .
10
10
11
11
The memory layout of a ` union ` is undefined by default, but the ` #[repr(...)] `
12
12
attribute can be used to fix a layout.
You can’t perform that action at this time.
0 commit comments