Skip to content

Commit f9945c0

Browse files
committed
be more explicit; add some structure
1 parent 24c0a88 commit f9945c0

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

src/items/unions.md

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ The key property of unions is that all fields of a union share common storage.
2020
As a result writes to one field of a union can overwrite its other fields, and
2121
size of a union is determined by the size of its largest field.
2222

23+
## Initialization of a union
24+
2325
A value of a union type can be created using the same syntax that is used for
2426
struct types, except that it must specify exactly one field:
2527

@@ -37,15 +39,17 @@ struct fields:
3739
let f = u.f1;
3840
```
3941

42+
## Reading and writing union fields
43+
4044
Unions have no notion of an "active field". Instead, every union access just
4145
interprets the storage at the type of the field used for the access. Reading a
4246
union field reads the bits of the union at the field's type. Fields might have a
4347
non-zero offset (except when `#[repr(C)]` is used); in that case the bits
4448
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
4953
writing to the type used for reading.
5054

5155
Consequently, all reads of union fields have to be placed in `unsafe` blocks:
@@ -72,6 +76,8 @@ u.f1 = 2;
7276
Commonly, code using unions will provide safe wrappers around unsafe union
7377
field accesses.
7478

79+
## Pattern matching on unions
80+
7581
Another way to access union fields is to use pattern matching. Pattern matching
7682
on union fields uses the same syntax as struct patterns, except that the pattern
7783
must 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+
124132
Since union fields share common storage, gaining write access to one field of a
125133
union can give write access to all its remaining fields. Borrow checking rules
126134
have to be adjusted to account for this fact. As a result, if one field of a

0 commit comments

Comments
 (0)