25.7 Rust Unions

Rust unions resemble C unions, enabling multiple fields to share the same underlying memory. Unlike Rust enums, unions do not track which variant is currently active, so accessing union fields is inherently unsafe.

#![allow(unused)]
fn main() {
union MyUnion {
    int_val: u32,
    float_val: f32,
}

fn union_example() {
    let u = MyUnion { int_val: 0x41424344 };
    unsafe {
        // Reading from a union field reinterprets the bits.
        println!("int: 0x{:X}, float: {}", u.int_val, u.float_val);
    }
}
}

Since the compiler does not know which field is valid at any point, you must ensure you only read the field that was last written. Otherwise, you risk undefined behavior.