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.
union IntOrFloat { i: u32, f: f32, }
Try it
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.
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
[#[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
ManuallyDropand drop them yourself, as the second example shows. - Pattern matching works on a single field, such as
let U { i } = u;, and also requiresunsafe. - Prefer
enumfor tagged alternatives, and preferf32::to_bitsoru32::from_ne_bytesfor plain bit reinterpretation of numbers; they are safe. - Padding bytes are uninitialized. Reading them through a different field is undefined behavior.
unionis a contextual keyword: it can still be used as an identifier outside a declaration.
Related
enum,struct,unsafe- Lessons: Unsafe Rust, Memory layout, Working with C (FFI)