@@ -20,6 +20,8 @@ The key property of unions is that all fields of a union share common storage.
20
20
As a result writes to one field of a union can overwrite its other fields, and
21
21
size of a union is determined by the size of its largest field.
22
22
23
+ ## Initialization of a union
24
+
23
25
A value of a union type can be created using the same syntax that is used for
24
26
struct types, except that it must specify exactly one field:
25
27
@@ -37,15 +39,17 @@ struct fields:
37
39
let f = u.f1;
38
40
```
39
41
42
+ ## Reading and writing union fields
43
+
40
44
Unions have no notion of an "active field". Instead, every union access just
41
45
interprets the storage at the type of the field used for the access. Reading a
42
46
union field reads the bits of the union at the field's type. Fields might have a
43
47
non-zero offset (except when ` #[repr(C)] ` is used); in that case the bits
44
48
starting at the offset of the fields are read. It is the programmer's
45
- responsibility to make sure that the data is valid at that type. Failing to do
46
- so results in undefined behavior. For example, reading the value ` 3 ` at type
47
- ` bool ` is undefined behavior. Effectively, writing to and then reading from a
48
- ` #[repr(C)] ` union is analogous to a [ ` transmute ` ] from the type used for
49
+ responsibility to make sure that the data is valid at the field's type. Failing
50
+ to do so results in undefined behavior. For example, reading the value ` 3 ` at
51
+ type ` bool ` is undefined behavior. Effectively, writing to and then reading from
52
+ a ` #[repr(C)] ` union is analogous to a [ ` transmute ` ] from the type used for
49
53
writing to the type used for reading.
50
54
51
55
Consequently, all reads of union fields have to be placed in ` unsafe ` blocks:
@@ -72,6 +76,8 @@ u.f1 = 2;
72
76
Commonly, code using unions will provide safe wrappers around unsafe union
73
77
field accesses.
74
78
79
+ ## Pattern matching on unions
80
+
75
81
Another way to access union fields is to use pattern matching. Pattern matching
76
82
on union fields uses the same syntax as struct patterns, except that the pattern
77
83
must specify exactly one field. Since pattern matching is like reading the union
@@ -121,6 +127,8 @@ fn is_zero(v: Value) -> bool {
121
127
}
122
128
```
123
129
130
+ ## References to union fields
131
+
124
132
Since union fields share common storage, gaining write access to one field of a
125
133
union can give write access to all its remaining fields. Borrow checking rules
126
134
have to be adjusted to account for this fact. As a result, if one field of a
0 commit comments