Unions

Unions are like enums, but you need to track the active field yourself:

  1. #[repr(C)]
  2. union MyUnion {
  3. i: u8,
  4. b: bool,
  5. }
  6. fn main() {
  7. let u = MyUnion { i: 42 };
  8. println!("int: {}", unsafe { u.i });
  9. println!("bool: {}", unsafe { u.b }); // Undefined behavior!
  10. }

Unions are very rarely needed in Rust as you can usually use an enum. They are occasionally needed for interacting with C library APIs.

If you just want to reinterpret bytes as a different type, you probably want std::mem::transmute or a safe wrapper such as the zerocopy crate.