25.7 Rust Unions

Rust unions are similar to C unions, allowing multiple fields to occupy the same underlying memory. Unlike Rust enums, unions do not track which variant is currently active, so accessing a union field 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 given time, you must ensure you only read the field that was last written. Otherwise, you risk undefined behavior.