Skip to content

Commit c3d23c2

Browse files
committed
unions have no active field
1 parent e57b2ee commit c3d23c2

File tree

1 file changed

+15
-10
lines changed

1 file changed

+15
-10
lines changed

src/items/unions.md

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -29,18 +29,22 @@ struct types, except that it must specify exactly one field:
2929
let u = MyUnion { f1: 1 };
3030
```
3131

32-
The expression above creates a value of type `MyUnion` with active field `f1`.
33-
Active field of a union can be accessed using the same syntax as struct fields:
32+
The expression above creates a value of type `MyUnion` and initializes the
33+
storage using field `f1`. The union can be accessed using the same syntax as
34+
struct fields:
3435

3536
```rust,ignore
3637
let f = u.f1;
3738
```
3839

39-
Inactive fields can be accessed as well (using the same syntax) if they are
40-
sufficiently layout compatible with the current value kept by the union.
41-
Reading incompatible fields results in undefined behavior. However, the active
42-
field is not generally known statically, so all reads of union fields have to
43-
be placed in `unsafe` blocks.
40+
Unions have no notion of an "active field". Instead, every union access just
41+
interprets the storage at the type of the field used for the access. The effect
42+
of reading a union with a different field than it was written to is that of
43+
calling [`transmute`]. Reading data at a bad type results in undefined behavior
44+
(for example, reading the value `3` at type `bool`).
45+
46+
However, which fields are safe to read and which not is generally not known
47+
statically, so all reads of union fields have to be placed in `unsafe` blocks.
4448

4549
```rust
4650
# union MyUnion { f1: u32, f2: f32 }
@@ -65,9 +69,9 @@ Commonly, code using unions will provide safe wrappers around unsafe union
6569
field accesses.
6670

6771
Another way to access union fields is to use pattern matching. Pattern matching
68-
on union fields uses the same syntax as struct patterns, except that the
69-
pattern must specify exactly one field. Since pattern matching accesses
70-
potentially inactive fields it has to be placed in `unsafe` blocks as well.
72+
on union fields uses the same syntax as struct patterns, except that the pattern
73+
must specify exactly one field. Since pattern matching is like reading the union
74+
with a particular field, it has to be placed in `unsafe` blocks as well.
7175

7276
```rust
7377
# union MyUnion { f1: u32, f2: f32 }
@@ -149,3 +153,4 @@ in [RFC 1897 "Unions v1.2"](https://github.com/rust-lang/rfcs/pull/1897).
149153
[_Generics_]: items/generics.html
150154
[_WhereClause_]: items/generics.html#where-clauses
151155
[_StructFields_]: items/structs.html
156+
[`transmute`]: ../../std/mem/fn.transmute.html

0 commit comments

Comments
 (0)