Union types in Rust are defined using the union keyword to create a type where all fields share the same memory address, allowing only one field to be active at a time. Because accessing union fields is unsafe, you must wrap the access in an unsafe block to prevent memory safety violations.
union MyUnion {
integer: i32,
float: f32,
}
fn main() {
let u = MyUnion { integer: 42 };
unsafe {
println!("Integer: {}", u.integer);
}
}