Sub topic 11
Reading and Writing Union Fields
This chapter assumes you know how Rust lays out structs and enums, how Copy and Drop work, and what raw pointers and undefined behavior are from earlier chapters. By the end you will be able to declare a union, read and write its fields, and wrap one in a safe tagged type.
What a union is
A union is a type whose fields all share the same memory. A struct stores its fields side by side. A union stores them on top of each other, so its size is the size of its largest field, rounded up for alignment. At any moment the bytes hold one value, and each field is a different way to view those bytes.
C programmers use unions to save space, to reinterpret bits, and to describe foreign data. Rust has unions mainly for the same reasons, and especially for talking to C code.
#[repr(C)]
union IntOrFloat {
i: u32,
f: f32,
}
fn main() {
let mut u = IntOrFloat { f: 1.0 };
// SAFETY: both fields are 4 bytes, and every bit pattern is a valid u32.
let bits = unsafe { u.i };
println!("{bits:#010x}");
// Writing a 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 and then 2. The first value is the bit pattern of 1.0f32. The second is the float whose bits are 0x40000000.
Three details of the declaration matter:
- You build a union by naming exactly one field:
IntOrFloat { f: 1.0 }. Naming zero or two fields is a compile error. #[repr(C)]gives the union C's layout rules. Without it, Rust does not promise that fields start at offset 0, so reinterpreting bytes between fields is not guaranteed to work. Use#[repr(C)]whenever you read a field other than the one you wrote.- Unions have no tag. The compiler does not record which field is active, so it cannot check your reads.
Why reading is unsafe and writing is not
Reading a field means interpreting the shared bytes as that field's type. The compiler cannot know whether those bytes form a valid value of that type. So reading a union field is one of the five unsafe operations.
Writing is different. Assigning to a field only stores bytes, and no value of another type is observed. A plain assignment to a union field is therefore safe, as the u.i = 0x4000_0000; line above shows.
The diagram shows both directions through the same four bytes.
The validity rule
The unsafe block on a read is your promise that the bytes are valid for the field's type. Types differ in how many bit patterns they accept.
| Field type | Valid bit patterns | Risk when reading |
|---|---|---|
| `u32`, `i64`, `f32`, `f64` | Every initialized pattern | Only uninitialized bytes |
| `bool` | `0` and `1` only | Any other byte is undefined behavior |
| `char` | Unicode scalar values only | Surrogates and values above `0x10FFFF` are UB |
| `&T`, `Box<T>`, `NonNull<T>` | Non-null, aligned, pointing to a valid `T` | Almost any other pattern is UB |
| Enums | Only the declared discriminants | Other values are UB |
Here is a union where the check passes and where it would fail.
#[repr(C)]
union ByteOrBool {
byte: u8,
flag: bool,
}
fn main() {
let u = ByteOrBool { byte: 1 };
// SAFETY: the byte is 1, which is a valid bool (true).
let flag = unsafe { u.flag };
println!("{flag}");
// Writing `ByteOrBool { byte: 2 }` is safe, but reading `.flag` from it
// would be undefined behavior, because 2 is not a valid bool.
}Uninitialized and padding bytes
Fields of different sizes cause a second problem. Take union Wide { small: u8, big: u32 }. If you write small, only 1 of the 4 bytes is initialized. Reading big then reads 3 uninitialized bytes. Integers must not contain uninitialized bytes, so this is undefined behavior even though every u32 pattern is valid.
The same applies to padding inside a struct field. Writing a struct that has padding and reading its bytes through an integer field exposes the padding. When you need to view a value as bytes, use MaybeUninit<u8> fields, which are allowed to hold uninitialized data.
What a union field may contain
Rust restricts the field types of a union so that it never has to drop a value it cannot identify. A field must be one of:
- a
Copytype, - a
ManuallyDrop<T>, - a reference or tuple/array of these.
A field of type String is rejected. If it were allowed, the compiler would not know whether to run its destructor when the union went out of scope. The union never runs drop glue for its fields. With ManuallyDrop<T> you take responsibility for dropping the value yourself.
A union implements Copy only if you ask for it, and only when all fields are Copy. #[derive(Clone, Copy)] works on such unions.
Borrowing and pattern matching
Several rules follow from the shared storage.
- Borrowing a field borrows the whole union. If you hold
&mut u.i, you cannot touchu.fat the same time. This keeps safe code from creating two references to the same bytes with different types. - Matching on a union is unsafe, and a pattern must name exactly one field:
match u { IntOrFloat { i: 0 } => ..., IntOrFloat { f } => ... }. - Taking a raw pointer to a field with
&raw const u.ior&raw mut u.iis safe, because no read happens. Dereferencing that pointer is the unsafe step.
Do not use a union for plain bit casts
Reinterpreting a float as an integer is common, but a union is rarely the best tool. Standard methods express the intent and need no unsafe:
f32::to_bitsandf32::from_bits,u32::to_le_bytesandu32::from_le_bytes,std::mem::transmutefor the rare case with no method, which is also unsafe.
Reserve unions for cases where a library API cannot express the layout. These are mostly foreign structs that C defines as unions, and tagged types where you control the tag.
A safe tagged union
Rust's enum already stores a tag next to its payload, so you seldom need to build this yourself. Doing it once shows the rule for safe unions: keep the tag and the union together in one private struct, and let only your methods read the union.
use std::mem::ManuallyDrop;
#[repr(C)]
union Payload {
number: i64,
text: ManuallyDrop<String>,
}
enum Tag {
Number,
Text,
}
pub struct Value {
tag: Tag,
payload: Payload,
}
impl Value {
pub fn number(n: i64) -> Self {
Value { tag: Tag::Number, payload: Payload { number: n } }
}
pub fn text(s: String) -> Self {
Value {
tag: Tag::Text,
payload: Payload { text: ManuallyDrop::new(s) },
}
}
pub fn as_number(&self) -> Option<i64> {
match self.tag {
// SAFETY: the tag is Number, so `number` was the last field written.
Tag::Number => Some(unsafe { self.payload.number }),
Tag::Text => None,
}
}
pub fn as_text(&self) -> Option<&str> {
match self.tag {
Tag::Number => None,
// SAFETY: the tag is Text, so `text` holds a live String.
Tag::Text => Some(unsafe { self.payload.text.as_str() }),
}
}
}
impl Drop for Value {
fn drop(&mut self) {
if let Tag::Text = self.tag {
// SAFETY: the tag is Text, so `text` is initialized, and this
// is the only place that drops it.
unsafe { ManuallyDrop::drop(&mut self.payload.text) };
}
}
}
fn main() {
let a = Value::number(7);
let b = Value::text(String::from("hello"));
println!("{:?} {:?}", a.as_number(), a.as_text());
println!("{:?} {:?}", b.as_number(), b.as_text());
}The output is Some(7) None and then None Some("hello").
This type is sound because of three facts:
- The fields
tagandpayloadare private, and the only constructors set both together, so they cannot disagree. - Every unsafe read first checks the tag.
- The
Dropimplementation drops theStringexactly once, and only when it exists. Without it, the string's heap memory would leak.
If you added a method that changed payload without updating tag, the type would stop being sound. That is why the review habit from the previous chapters applies here: the safety argument covers the whole module, not only the unsafe blocks.
Common mistakes
- Reading a field with a narrower valid range than the one written, such as
bool,char, references, or enums. - Reading a larger field after writing a smaller one, which exposes uninitialized bytes.
- Omitting
#[repr(C)]and assuming fields overlap at offset 0. - Holding
&mutto one field and expecting to use another field at the same time. The borrow checker rejects this, so the fix is to restructure the code. - Using a union to cast bits when
to_bitsorto_le_byteswould do.
Miri, covered in a later chapter, detects reads of uninitialized bytes and invalid bool, char, and reference values from union fields. Run your tests under it whenever you write a union.
Exercise
A union is declared as #[repr(C)] union Pair { small: u8, big: u32 }. Your code runs let p = Pair { small: 5 }; and then let n = unsafe { p.big };. Is this sound? Explain, and state one way to fix it.
Show answer
It is not sound. Only the first byte of p was initialized by the write to small. Reading big reads three uninitialized bytes into a u32, which is undefined behavior even though every u32 bit pattern is valid. One fix is to construct the union through the larger field, Pair { big: 5 }, and read small instead, since that reads only initialized bytes. Another is to avoid the union and use u32::from(5u8).
Exercise
Why does Rust reject union Bad { s: String, n: u64 }, and what change makes the declaration compile?
Show answer
The compiler cannot know which field is active, so it could not decide whether to run String's destructor when the union goes out of scope. Union fields must be Copy, ManuallyDrop<T>, or references. Changing the field to s: ManuallyDrop<String> compiles, and you then take responsibility for calling ManuallyDrop::drop when the string is active.
Exercise
In the Value type above, what goes wrong if as_text is changed to skip the tag check and read self.payload.text directly?
Show answer
If the tag is Number, the union holds an i64 and the ManuallyDrop<String> view treats those bytes as a string's pointer, capacity, and length. Calling as_str on it dereferences an invalid pointer, which is undefined behavior. A safe public method must not allow this, so the tag check is what makes as_text sound.