@@ -20,6 +20,8 @@ The key property of unions is that all fields of a union share common storage.
2020As a result writes to one field of a union can overwrite its other fields, and
2121size of a union is determined by the size of its largest field.
2222
23+ ## Initialization of a union
24+
2325A value of a union type can be created using the same syntax that is used for
2426struct types, except that it must specify exactly one field:
2527
@@ -37,15 +39,17 @@ struct fields:
3739let f = u.f1;
3840```
3941
42+ ## Reading and writing union fields
43+
4044Unions have no notion of an "active field". Instead, every union access just
4145interprets the storage at the type of the field used for the access. Reading a
4246union field reads the bits of the union at the field's type. Fields might have a
4347non-zero offset (except when ` #[repr(C)] ` is used); in that case the bits
4448starting 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
4953writing to the type used for reading.
5054
5155Consequently, all reads of union fields have to be placed in ` unsafe ` blocks:
@@ -72,6 +76,8 @@ u.f1 = 2;
7276Commonly, code using unions will provide safe wrappers around unsafe union
7377field accesses.
7478
79+ ## Pattern matching on unions
80+
7581Another way to access union fields is to use pattern matching. Pattern matching
7682on union fields uses the same syntax as struct patterns, except that the pattern
7783must specify exactly one field. Since pattern matching is like reading the union
@@ -121,6 +127,8 @@ fn is_zero(v: Value) -> bool {
121127}
122128```
123129
130+ ## References to union fields
131+
124132Since union fields share common storage, gaining write access to one field of a
125133union can give write access to all its remaining fields. Borrow checking rules
126134have to be adjusted to account for this fact. As a result, if one field of a
0 commit comments