keyword
Rust union: declare overlapping fields
A union stores alternative field representations in overlapping storage. Unlike an enum, it does not track an active variant. Reading a field requires unsafe code and a valid representation. Expected output (not executed): 9 Why: The program reads exactly the field initialized with a valid value. Common mistake: Do not use a union as a tagged enum. Reading an arbitrary field can violate validity requirements.
Formal Syntax & Structure
rust syntaxrust
union Name { field: Type, other: Type }Working Example
Example Snippetrust
union Number { unsigned: u32, signed: i32 }
fn main() { let n = Number { unsigned: 9 }; // SAFETY: the unsigned field was just initialized with a valid u32. println!("{}", unsafe { n.unsigned });}