Sub topic 11
Reading and writing union fields
This chapter assumes you know the five unsafe operations, raw pointers, and the idea of a safety contract from the earlier chapters. You should also be comfortable with Copy types and #[repr(C)].
What a union is
A union is a type whose fields all share the same memory. The union is as large as its largest field. Only one field holds a meaningful value at a time, and the compiler does not track which one.
union IntOrFloat {
i: u32,
f: f32,
}
fn main() {
let mut u = IntOrFloat { f: 1.0 };
// SAFETY: the union was initialized through `f`, which fills all four
// bytes, and every bit pattern is a valid u32.
let bits = unsafe { u.i };
println!("{bits:#010x}");
// Writing a Copy field is safe.
u.i = 0x4000_0000;
// SAFETY: every bit pattern is a valid f32.
let f = unsafe { u.f };
println!("{f}");
}This prints 0x3f800000, then 2. The write u.i = ... needs no unsafe. The reads need it.
Why reads are unsafe and writes are not
Writing a field only stores bytes. It cannot produce an invalid value. Reading a field reinterprets whatever bytes are there as the field's type. If those bytes are not a valid value of that type, you get undefined behavior.
| Operation | Needs `unsafe` | Reason |
|---|---|---|
| Write a `Copy` field | No | Storing bytes cannot create an invalid value |
| Read a field | Yes | The bytes might be invalid for that type |
| Match on a union field in a pattern | Yes | A pattern reads the field |
| Take a reference to a field | Yes | The reference promises a valid value |
Writing a field whose type has a destructor is restricted. Union fields must be Copy, ManuallyDrop<T>, or a reference. The compiler will not run drop glue for a union, because it cannot know which field is live.
Validity still applies
Reading a field is only sound if the bytes are valid for that field's type. Every u32 bit pattern is a valid f32, and the reverse holds too. That is why the example above is sound. A bool is different, because only 0 and 1 are valid. Reading a bool field from a union that holds the byte 2 is undefined behavior, even if you never use the result.
Also, a field that is smaller than the union does not initialize all of its bytes. If you write a u8 field into a u32 union, the other three bytes are uninitialized. Reading the u32 field then reads uninitialized memory, which is undefined behavior.
Keeping the live field in a tag
Because the compiler does not track the active field, you usually track it yourself. A tag plus a union gives you a hand-built enum. Keep the fields private so that only your constructors can set the tag.
#[repr(C)]
union Raw {
int: i32,
float: f32,
}
enum Tag {
Int,
Float,
}
struct Tagged {
tag: Tag,
raw: Raw,
}
impl Tagged {
fn from_int(n: i32) -> Self {
Tagged { tag: Tag::Int, raw: Raw { int: n } }
}
fn from_float(x: f32) -> Self {
Tagged { tag: Tag::Float, raw: Raw { float: x } }
}
fn as_int(&self) -> Option<i32> {
match self.tag {
// SAFETY: the tag is Int only when `int` was the last field written.
Tag::Int => Some(unsafe { self.raw.int }),
Tag::Float => None,
}
}
fn as_float(&self) -> Option<f32> {
match self.tag {
Tag::Int => None,
// SAFETY: the tag is Float only when `float` was the last field written.
Tag::Float => Some(unsafe { self.raw.float }),
}
}
}
fn main() {
let a = Tagged::from_int(7);
let b = Tagged::from_float(2.5);
println!("{:?} {:?}", a.as_int(), a.as_float());
println!("{:?} {:?}", b.as_int(), b.as_float());
}The public methods are safe. Callers cannot reach raw or tag, so they cannot make the tag disagree with the data. This is the safe-abstraction pattern from the earlier chapter, applied to a union.
When not to use a union
In ordinary Rust, an enum does this job with no unsafe. For bit reinterpretation between plain number types, prefer safe methods such as f32::to_bits and f32::from_bits. Reach for a union mainly for C interop, where a C header defines a union you must match, and for low-level layouts you cannot express otherwise.
Exercise
A union has a u8 field and a u32 field. You write u.byte = 1; and then read u.word. Why is the read undefined behavior, and why was the write allowed without unsafe?
Show answer
The write initializes only one byte, so the other three bytes of the u32 are uninitialized, and reading uninitialized memory as an integer is undefined behavior. The write needed no unsafe because storing bytes into a Copy field cannot create an invalid value. Only the read reinterprets bytes and can break validity.