Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Keywords and Statements

The union keyword

Reference for Rust union: declaring untagged unions, why reads are unsafe, ManuallyDrop fields, repr(C) layout, pattern matching and when to prefer enums.

A union looks like a struct, but all of its fields share the same memory. Only one field holds a meaningful value at a time, and the compiler does not remember which one. Because of that, writing a field is safe, while reading a field is unsafe: you promise that the bytes stored there are a valid value of the field's type.

Unions exist mainly for talking to C code, for reinterpreting bytes, and for building low-level data structures. For ordinary "one of several shapes" data, use an enum, which stores a tag and is fully safe.

Rust
union IntOrFloat {
    i: u32,
    f: f32,
}

Try it

Rust Reading the same bytes two ways

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust A tagged wrapper around a union

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
[#[repr(C)]] [pub] union Name<generics> {
    [pub] field: Type,
    ...
}

let u = Name { field: value };   // exactly one field
let x = unsafe { u.field };      // read
u.field = value;                 // write (safe for Copy / ManuallyDrop fields)
Part Description
Fields Each field starts at offset 0 of the union (with repr(C)). The union is as large as its largest field, rounded up to its alignment.
Initialization A union literal names exactly one field.
Field types Must be Copy, ManuallyDrop<T>, a reference, or a tuple/array of those. Types with drop glue (such as a bare String) are rejected, because the compiler would not know whether to drop them.

Errors and edge cases: reading a field whose bytes are not valid for its type (for example a bool that holds 2, or a reference that holds garbage) is undefined behavior.

Usage notes

  • Reads are unsafe, writes are safe. Assigning to a field never reads old data, so it is safe as long as the field does not need dropping.
  • Use #[repr(C)] when you need a layout that matches a C union. Without it, the compiler picks the layout.
  • Unions never run drop glue for their fields. Wrap owning types in ManuallyDrop and drop them yourself, as the second example shows.
  • Pattern matching works on a single field, such as let U { i } = u;, and also requires unsafe.
  • Prefer enum for tagged alternatives, and prefer f32::to_bits or u32::from_ne_bytes for plain bit reinterpretation of numbers; they are safe.
  • Padding bytes are uninitialized. Reading them through a different field is undefined behavior.
  • union is a contextual keyword: it can still be used as an identifier outside a declaration.