Sub topic 1
Why Rust has an unsafe escape hatch
Prerequisites
This chapter assumes you already know:
- Ownership, borrowing, and lifetimes in safe Rust.
- References, slices, and structs.
- Traits and generics basics.
- How to build and run a program with Cargo.
You do not need any prior experience with unsafe.
The problem unsafe solves
Safe Rust rejects any program whose memory safety the compiler cannot prove. That rule is conservative by design. The compiler sometimes rejects programs that are actually correct, because proving them correct takes reasoning the compiler cannot do.
Some work also cannot be expressed in safe Rust at all:
- Talking to hardware or the operating system, which means reading and writing specific memory addresses.
- Calling libraries written in C.
- Building core types such as
Vec<T>,Rc<T>, orMutex<T>, which manage raw memory themselves.
Rust handles these cases with unsafe. It is a marked region where you, not the compiler, take responsibility for certain rules.
What unsafe does and does not change
An unsafe block does not turn off the borrow checker. It does not turn off type checking either. Inside it, ownership, lifetimes, and moves are checked exactly as before.
What unsafe does is unlock a short list of extra operations. Each one has rules the compiler cannot verify. Later chapters cover the full list. The first example shows one of them, dereferencing a raw pointer:
fn main() {
let mut num = 5;
let p = &mut num as *mut i32;
unsafe {
*p += 1;
println!("num through pointer: {}", *p);
}
}Creating p is safe. Reading or writing through it needs unsafe, because the compiler cannot tell whether p points to valid memory. Here you know it does, because it points at the local num.
The contract model
Think of unsafe as a promise. When you write an unsafe block, you promise that every rule the compiler cannot check is upheld. If you break the promise, the program has undefined behavior. Undefined behavior means the language makes no guarantees about what happens. The program may crash, return wrong answers, or appear to work until a compiler upgrade changes the result.
This changes who is responsible for what:
| Code | Who checks memory safety | Result if a rule is broken |
|---|---|---|
| Safe Rust | The compiler | A compile error |
| `unsafe` block | You | Undefined behavior |
The key design goal is that safe Rust cannot cause undefined behavior. The unsafe code underneath must be written so that no safe caller can trigger it. That idea is called soundness. A safe function that can cause undefined behavior when called with some safe input is unsound, even if the bug is inside its unsafe block.
Common mistakes
- Thinking
unsafemeans "the compiler stops checking." It only unlocks specific operations. Everything else is still checked. - Treating a working run as proof of correctness. Undefined behavior can pass every test you run and fail later.
- Using
unsafeto silence a borrow checker error. If safe Rust rejects your code, first look for a safe restructuring. Reaching forunsafeto bypass the error usually creates a real bug. - Writing
unsafewith no explanation. Anyone reading the code needs to know why it is valid.
Where this tutorial goes next
The rest of the tutorial builds on this model. You will learn what undefined behavior is in detail, the five operations that unsafe unlocks, and how to write functions that state their requirements. The goal is to wrap unsafe code so that callers never need to write unsafe themselves.
Exercise
An unsafe block contains code that moves a String and then uses it again. Does the compiler accept it? Explain.
Show answer
No. unsafe does not disable the borrow checker or move checking. Use after move is still a compile error inside an unsafe block.
Exercise
A safe function fn get(v: &Vec<i32>, i: usize) -> i32 uses unsafe internally and reads out of bounds when i is too large. Is the function sound? Why or why not?
Show answer
It is unsound. A safe caller can pass an out-of-range index using only safe code and trigger undefined behavior. The function should check the index first, or be marked unsafe fn so callers must uphold the requirement.