expression
Interpret shared union storage with a known valid field
Union fields overlap in storage. The programmer must establish validity for the particular field being read; a union does not record a variant tag. This case uses integer fields with the same size and no invalid bit patterns. A tagged enum is usually preferable. Expected stdout (not executed): 4294967294 Common mistake: Reading a bool or reference field after writing unrestricted integer bits.
Formal Syntax & Structure
rust syntaxrust
#[repr(C)] union Word { signed: i32, unsigned: u32 }Working Example
Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() { #[repr(C)] union Word { signed: i32, unsigned: u32 } let word = Word { signed: -2 }; // SAFETY: repr(C) places both fields at offset zero; the i32 initializes all four bytes, // and every u32 bit pattern is valid. There is no concurrent mutation. let bits = unsafe { word.unsigned }; println!("{bits}");}