Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mention how unions interact with dropping #897

Merged
merged 2 commits into from
Oct 18, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/items/unions.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,16 @@ u.f1 = 2;
Commonly, code using unions will provide safe wrappers around unsafe union
field accesses.

## Unions and `Drop`

When a union is dropped, it cannot know which of its fields needs to be dropped.
For this reason, all union fields must either be of a `Copy` type or of the
shape [`ManuallyDrop<_>`]. This ensures that a union does not need to drop
anything when it goes out of scope.

Like for structs and enums, it is possible to `impl Drop` for a union to
manually define what happens when it gets dropped.

## Pattern matching on unions

Another way to access union fields is to use pattern matching. Pattern matching
Expand Down Expand Up @@ -167,3 +177,4 @@ checking, etc etc etc).
[_WhereClause_]: generics.md#where-clauses
[_StructFields_]: structs.md
[`transmute`]: ../../std/mem/fn.transmute.html
[`ManuallyDrop<_>`]: ../../std/mem/struct.ManuallyDrop.html
2 changes: 1 addition & 1 deletion src/types/union.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ a [`union` item][item].
Unions have no notion of an "active field". Instead, every union access
transmutes parts of the content of the union to the type of the accessed
field. Since transmutes can cause unexpected or undefined behaviour, `unsafe` is
required to read from a union field or to write to a field that doesn't
required to read from a union field, or to write to a field that doesn't
implement [`Copy`]. See the [item] documentation for further details.

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