expression
Read an initialized union field
Union fields overlap and Rust does not track a currently active field. Reading requires the programmer to establish that the chosen field has a valid representation. This example reads exactly the integer field that was initialized, with no reinterpretation or uninitialized bytes. Expected stdout (not executed): 31 Common mistake: Assuming every field is valid after writing one union field.
Formal Syntax & Structure
rust syntaxrust
unsafe { value.field }Working Example
Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() { #[repr(C)] union Payload { number: u32, real: f32 } let payload = Payload { number: 31 }; // SAFETY: number was initialized and no other field was written. let number = unsafe { payload.number }; println!("{number}");}