@@ -29,18 +29,22 @@ struct types, except that it must specify exactly one field:
29
29
let u = MyUnion { f1 : 1 };
30
30
```
31
31
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:
34
35
35
36
``` rust,ignore
36
37
let f = u.f1;
37
38
```
38
39
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.
44
48
45
49
``` rust
46
50
# union MyUnion { f1 : u32 , f2 : f32 }
@@ -65,9 +69,9 @@ Commonly, code using unions will provide safe wrappers around unsafe union
65
69
field accesses.
66
70
67
71
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.
71
75
72
76
``` rust
73
77
# union MyUnion { f1 : u32 , f2 : f32 }
@@ -149,3 +153,4 @@ in [RFC 1897 "Unions v1.2"](https://github.com/rust-lang/rfcs/pull/1897).
149
153
[ _Generics_ ] : items/generics.html
150
154
[ _WhereClause_ ] : items/generics.html#where-clauses
151
155
[ _StructFields_ ] : items/structs.html
156
+ [ `transmute` ] : ../../std/mem/fn.transmute.html
0 commit comments