Skip to content

Commit d850fd2

Browse files
authored
Merge pull request #897 from RalfJung/union
mention how unions interact with dropping
2 parents e526381 + 0d6f579 commit d850fd2

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

src/items/unions.md

+11
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,16 @@ u.f1 = 2;
7979
Commonly, code using unions will provide safe wrappers around unsafe union
8080
field accesses.
8181

82+
## Unions and `Drop`
83+
84+
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.
88+
89+
Like for structs and enums, it is possible to `impl Drop` for a union to
90+
manually define what happens when it gets dropped.
91+
8292
## Pattern matching on unions
8393

8494
Another way to access union fields is to use pattern matching. Pattern matching
@@ -167,3 +177,4 @@ checking, etc etc etc).
167177
[_WhereClause_]: generics.md#where-clauses
168178
[_StructFields_]: structs.md
169179
[`transmute`]: ../../std/mem/fn.transmute.html
180+
[`ManuallyDrop<_>`]: ../../std/mem/struct.ManuallyDrop.html

src/types/union.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ a [`union` item][item].
66
Unions have no notion of an "active field". Instead, every union access
77
transmutes parts of the content of the union to the type of the accessed
88
field. Since transmutes can cause unexpected or undefined behaviour, `unsafe` is
9-
required to read from a union field or to write to a field that doesn't
9+
required to read from a union field, or to write to a field that doesn't
1010
implement [`Copy`]. See the [item] documentation for further details.
1111

1212
The memory layout of a `union` is undefined by default, but the `#[repr(...)]`

0 commit comments

Comments
 (0)