@@ -20,6 +20,16 @@ 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
+ Union field types are restricted to the following subset of types:
24
+ - ` Copy ` types
25
+ - References (` &T ` and ` &mut T ` for arbitrary ` T ` )
26
+ - ` ManuallyDrop<T> ` (for arbitrary ` T ` )
27
+ - Tuples and arrays containing only allowed union field types
28
+
29
+ This restriction ensures, in particular, that union fields never need to be
30
+ dropped. Like for structs and enums, it is possible to ` impl Drop ` for a union
31
+ to manually define what happens when it gets dropped.
32
+
23
33
## Initialization of a union
24
34
25
35
A value of a union type can be created using the same syntax that is used for
@@ -67,32 +77,13 @@ unsafe {
67
77
}
68
78
```
69
79
70
- Writes to [ ` Copy ` ] or [ ` ManuallyDrop ` ] [ ManuallyDrop ] union fields do not
71
- require reads for running destructors, so these writes don't have to be placed
72
- in ` unsafe ` blocks
73
-
74
- ``` rust
75
- # use std :: mem :: ManuallyDrop ;
76
- union MyUnion { f1 : u32 , f2 : ManuallyDrop <String > }
77
- let mut u = MyUnion { f1 : 1 };
78
-
79
- // These do not require `unsafe`.
80
- u . f1 = 2 ;
81
- u . f2 = ManuallyDrop :: new (String :: from (" example" ));
82
- ```
83
-
84
80
Commonly, code using unions will provide safe wrappers around unsafe union
85
81
field accesses.
86
82
87
- ## Unions and ` Drop `
88
-
89
- When a union is dropped, it cannot know which of its fields needs to be dropped.
90
- For this reason, all union fields must either be of a [ ` Copy ` ] type or of the
91
- shape [ ` ManuallyDrop<_> ` ] [ ManuallyDrop ] . This ensures that a union does not
92
- need to drop anything when it goes out of scope.
93
-
94
- Like for structs and enums, it is possible to ` impl Drop ` for a union to
95
- manually define what happens when it gets dropped.
83
+ In contrast, writes to union fields are safe, since they just overwrite
84
+ arbitrary data, but cannot cause undefined behavior. (Note that union field
85
+ types can never have drop glue, so a union field write will never implicitly
86
+ drop anything.)
96
87
97
88
## Pattern matching on unions
98
89
0 commit comments