Sub topic 3
Unsafe Traits, Send, and Sync
Prerequisites: ownership, borrowing, lifetimes, traits, generics, and basic Cargo use. This chapter focuses on code the compiler cannot fully verify.
Unsafe traits: `Send` and `Sync`
Send means a value can be moved to another thread. Sync means a shared reference to a value can be used from multiple threads. Rust automatically implements these traits when a type's fields allow it.
An unsafe impl makes a promise that the compiler cannot check:
struct Handle(*mut u8);
// SAFETY: the pointed-to resource is thread-safe and has exclusive ownership.
unsafe impl Send for Handle {}An incorrect implementation can cause data races or invalid memory access. Implement these traits only when you can explain the thread-safety argument.
> callout warning > Send and Sync are separate promises. A type may safely move between threads without allowing shared access from several threads.
Calling C functions with `extern` blocks
Foreign functions have contracts written outside Rust. In the 2024 edition, declare them in an unsafe extern block and call them inside unsafe:
unsafe extern "C" {
fn abs(input: i32) -> i32;
}
fn main() {
// SAFETY: -3 is a valid i32 argument for C's abs function.
let result = unsafe { abs(-3) };
println!("{result}");
}The declaration must match the foreign function's real ABI and signature.
Reading and writing union fields
A union stores one value in shared memory. Writing a field is allowed, but reading is unsafe because Rust cannot know which field was most recently written.
union Number {
integer: u32,
decimal: f32,
}
fn main() {
let value = Number { integer: 42 };
// SAFETY: `integer` is the field initialized above.
let answer = unsafe { value.integer };
println!("{answer}");
}Uninitialized memory with `MaybeUninit`
MaybeUninit<T> reserves storage that may not contain a valid T. Call assume_init only after completely initializing it.
use std::mem::MaybeUninit;
fn main() {
let mut slot = MaybeUninit::<u32>::uninit();
slot.write(42);
// SAFETY: `slot` was initialized by `write`.
let value = unsafe { slot.assume_init() };
println!("{value}");
}Finding undefined behavior with Miri
Miri runs Rust programs in an interpreter and detects many invalid memory operations. Install and run it with:
rustup +nightly component add miri
cargo +nightly miri testKeeping unsafe small and reviewable
- Put unsafe operations in the smallest possible block.
- Document each block with a
SAFETYcomment. - Check nullness, alignment, initialization, bounds, and aliasing.
- Expose a safe API that validates inputs before entering unsafe code.
- Test boundary cases and run Miri where possible.
Exercise
Why is assume_init unsafe?
Show answer
Rust cannot verify that every byte contains a valid initialized value of type T; the programmer must prove that first.