@@ -66,14 +66,18 @@ unsafe {
66
66
}
67
67
```
68
68
69
- Writes to ` Copy ` union fields do not require reads for running destructors, so
70
- these writes don't have to be placed in ` unsafe ` blocks
69
+ Writes to [ ` Copy ` ] or [ ` ManuallyDrop ` ] [ ManuallyDrop ] union fields do not
70
+ require reads for running destructors, so these writes don't have to be placed
71
+ in ` unsafe ` blocks
71
72
72
73
``` rust
73
- # union MyUnion { f1 : u32 , f2 : f32 }
74
- # let mut u = MyUnion { f1 : 1 };
75
- #
74
+ # use std :: mem :: ManuallyDrop ;
75
+ union MyUnion { f1 : u32 , f2 : ManuallyDrop <String > }
76
+ let mut u = MyUnion { f1 : 1 };
77
+
78
+ // These do not require `unsafe`.
76
79
u . f1 = 2 ;
80
+ u . f2 = ManuallyDrop :: new (String :: from (" example" ));
77
81
```
78
82
79
83
Commonly, code using unions will provide safe wrappers around unsafe union
@@ -82,9 +86,9 @@ field accesses.
82
86
## Unions and ` Drop `
83
87
84
88
When a union is dropped, it cannot know which of its fields needs to be dropped.
85
- For this reason, all union fields must either be of a ` Copy ` type or of the
86
- shape [ ` ManuallyDrop<_> ` ] . This ensures that a union does not need to drop
87
- anything when it goes out of scope.
89
+ For this reason, all union fields must either be of a [ ` Copy ` ] type or of the
90
+ shape [ ` ManuallyDrop<_> ` ] [ ManuallyDrop ] . This ensures that a union does not
91
+ need to drop anything when it goes out of scope.
88
92
89
93
Like for structs and enums, it is possible to ` impl Drop ` for a union to
90
94
manually define what happens when it gets dropped.
@@ -177,4 +181,5 @@ checking, etc etc etc).
177
181
[ _WhereClause_ ] : generics.md#where-clauses
178
182
[ _StructFields_ ] : structs.md
179
183
[ `transmute` ] : ../../std/mem/fn.transmute.html
180
- [ `ManuallyDrop<_>` ] : ../../std/mem/struct.ManuallyDrop.html
184
+ [ `Copy` ] : ../../std/marker/trait.Copy.html
185
+ [ ManuallyDrop ] : ../../std/mem/struct.ManuallyDrop.html
0 commit comments