`unsafe`
unsafe is a keyword that opts a block, function, or trait impl out of some of Rust's guarantees. You become responsible for the invariants the compiler stopped checking.
Detailed Explanation
Safe Rust promises that a program which compiles does not have data races, dangling pointers, or invalid enum discriminants, unless you use unsafe incorrectly. unsafe is the hole. It does not turn the borrow checker off for ordinary references. It unlocks a short list of operations: dereference a raw pointer, call an unsafe fn, access a mutable static, implement an unsafe trait, and a few others such as union field access.
An unsafe fn is a function the caller must read before calling. The function documents extra requirements — this pointer is valid, this usize is a live index, this bool matches the allocation — and the caller writes unsafe { f(ptr) } to accept them. An unsafe block around a safe function does nothing useful. An unsafe impl Send for MyType asserts that MyType can cross threads, which the compiler cannot see if the type contains a raw pointer.
Undefined behaviour in Rust is a language-level list: use-after-free, data races, invalid values (false as a bool bit pattern that is not 0 or 1), violating aliasing rules with raw pointers, and so on. If you cause UB, the optimiser may delete your code or worse. unsafe is not a performance mode. It is a proof obligation. The usual style is a tiny unsafe block next to a comment that states the invariant you checked, wrapped in a safe API so callers never write unsafe themselves.
You need unsafe for FFI, for some zero-copy parsers, for custom smart pointers, and for talking to the hardware. You do not need it for typical application code. Vec, HashMap, and slices already wrap the unsafe they need. If you are writing unsafe to silence a borrow checker error, you are probably about to create a dangling pointer; restructure the data instead.
When you write unsafe: you can state the invariant in one sentence and you have no safe alternative. When you do not: the rest of the time. Review unsafe like you would review C.
Code Examples
fn first_mut(buf: &mut [u8]) -> Option<&mut u8> {
if buf.is_empty() {
return None;
}
// SAFETY: we just checked the slice is non-empty, so index 0 is in bounds.
Some(unsafe { buf.get_unchecked_mut(0) })
}
fn main() {
let mut bytes = [1, 2, 3];
if let Some(b) = first_mut(&mut bytes) {
*b = 9;
}
println!("{:?}", bytes); // prints: [9, 2, 3]
}Common Gotchas
UB is not a panic
A wrong `unsafe` can appear to work in debug and delete a branch in release. Never "try" an invariant.
`unsafe` does not disable the borrow checker
You still cannot hold `&` and `&mut` to the same safe reference. Raw pointers are the escape, and they have aliasing rules too (`noalias`).
Keep the `unsafe` block small
Compute the index in safe code. Put only the unchecked operation inside. Write the SAFETY comment against that line.
`unsafe impl Send` is a soundness claim
If the type contains `Rc` or a raw pointer to thread-local data, that impl is a bug the compiler will not catch.