@@ -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,13 +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
- union field reads the bits of the union at the field's type. It is the
43
- programmer's responsibility to make sure that the data is valid at that
44
- type. Failing to do so results in undefined behavior. For example, reading the
45
- value ` 3 ` at type ` bool ` is undefined behavior. Effectively, writing to and then
46
- reading from a union is analogous to a [ ` transmute ` ] from the type used for
46
+ union field reads the bits of the union at the field's type. Fields might have a
47
+ non-zero offset (except when ` #[repr(C)] ` is used); in that case the bits
48
+ starting at the offset of the fields are read. It is the programmer's
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
47
53
writing to the type used for reading.
48
54
49
55
Consequently, all reads of union fields have to be placed in ` unsafe ` blocks:
@@ -70,6 +76,8 @@ u.f1 = 2;
70
76
Commonly, code using unions will provide safe wrappers around unsafe union
71
77
field accesses.
72
78
79
+ ## Pattern matching on unions
80
+
73
81
Another way to access union fields is to use pattern matching. Pattern matching
74
82
on union fields uses the same syntax as struct patterns, except that the pattern
75
83
must specify exactly one field. Since pattern matching is like reading the union
@@ -119,6 +127,8 @@ fn is_zero(v: Value) -> bool {
119
127
}
120
128
```
121
129
130
+ ## References to union fields
131
+
122
132
Since union fields share common storage, gaining write access to one field of a
123
133
union can give write access to all its remaining fields. Borrow checking rules
124
134
have to be adjusted to account for this fact. As a result, if one field of a
0 commit comments