In Rust, what can code inside an `unsafe` block do that safe code cannot, and which compiler checks keep running inside it?
answer
- a short fixed list
- raw pointers, unsafe calls, statics
- unions and unsafe traits too
- borrow checker never sleeps
basics
~20 sAn unsafe block unlocks a few operations: dereferencing raw pointers, calling unsafe functions, using a static mut and reading union fields, while unsafe impl covers unsafe traits. Borrow checking, type checking and bounds checks all stay on.
solid answer
~40 sThe Book counts five superpowers: dereference a raw pointer, call an unsafe function or method, access or modify a `static mut`, implement an unsafe trait (with `unsafe impl`), and read union fields. The Reference adds rarer cases, such as calling a `#[target_feature]` function from code lacking that feature, or applying an unsafe attribute. Nothing else changes. References inside the block are still borrow-checked, so two `&mut v` still fail with E0499; types are still checked; `v[10]` still panics on its bounds check. If a block contains none of the unlocked operations, rustc warns ``unnecessary `unsafe` block``. What `unsafe` really does is move responsibility: the compiler stops checking those few operations and the author promises their preconditions hold, which is why reviewers want each block small and explained.
code
rust · 9 linesfn main() {
let mut v = vec![1, 2, 3];
unsafe {
let a = &mut v;
let b = &mut v; // still borrow-checked inside unsafe
a.push(4);
b.push(5);
}
}go deeper
Recite the five operations the Book lists and say plainly that borrow checking and type checking still run inside an unsafe block.
Explain unsafe as moving a few proofs from the compiler to the author, and back it with an E0499 that still fires inside the block.
Know the Reference's longer list, including target_feature calls and unsafe attributes, and argue for one small, commented block per operation in review.
Treat the short list as an audit boundary: because undefined behaviour can only arise through these operations, a team can search for, count and review exactly that code.
## What the keyword unlocks `unsafe` in Rust is not a mode that switches the compiler off. It unlocks a short, fixed list of operations that the compiler cannot prove harmless, and it moves the proof of those operations onto the programmer. The Rust Book calls them the five **unsafe superpowers**: 1. **Dereference a raw pointer** (`*const T` or `*mut T`), with `*p` or with a method such as `p.read()`. 2. **Call an unsafe function or method**, such as `slice::get_unchecked`, `ptr::read` or a foreign function. 3. **Access or modify a mutable static**, a `static mut` item. 4. **Implement an unsafe trait**, which is written `unsafe impl` rather than inside a block. 5. **Access fields of a union**: reading one is unsafe; the Reference exempts plain assignment to a field. The Reference's chapter on unsafety gives the complete list, and it is slightly longer than the Book's five. It adds calling a function marked `#[target_feature]` from code that does not enable the same features, declaring an `extern` block (which the 2024 edition writes as `unsafe extern`), and applying an unsafe attribute such as `#[unsafe(no_mangle)]`. Those last two belong to the material on foreign function calls; the five above are what everyday unsafe code uses. ## What it does not switch off Everything else the compiler checks still runs inside an `unsafe` block: - **The borrow checker.** References keep their rules: two live `&mut v` fail with E0499, exactly as in safe code. - **Type checking.** A mismatched type is still E0308; `unsafe` never lets you treat one type as another without an explicit conversion such as a pointer cast or `mem::transmute`. - **Lifetimes.** A reference that would outlive its referent is still rejected. - **Runtime checks in std.** `v[10]` on a three-element `Vec` still panics with "index out of bounds"; skipping the check means calling a different, unsafe method. - **Privacy and visibility.** A private field stays private; `unsafe` grants no access across module boundaries. The Book's wording is direct: `unsafe` "doesn't turn off the borrow checker or disable any of Rust's other safety checks." What you gain is the right to use raw pointers, which are not borrow-checked at all, and to call functions whose preconditions the compiler cannot see. ## Proof from the compiler The snippet in this question's code example puts two mutable borrows of one `Vec` inside an `unsafe` block. rustc 1.99.1 rejects it with ``error[E0499]: cannot borrow `v` as mutable more than once at a time``, and it also warns ``unnecessary `unsafe` block`` (the `unused_unsafe` lint), because nothing inside the block is one of the unlocked operations. That second message is a useful habit-breaker: an `unsafe` block around ordinary code does nothing at all. ## Where the keyword appears The same keyword shows up in several positions, and each one says who carries a proof obligation: | Position | Meaning | Who must uphold the condition | |---|---|---| | `unsafe fn` | calling it has preconditions the compiler cannot check | every caller | | `unsafe { ... }` | the author asserts the preconditions inside are met | the block's author | | `unsafe trait` | implementations must keep an extra contract | every implementor | | `unsafe impl` | the implementor asserts the contract holds | the impl's author | | `static mut` | any access may race or alias | every block that touches it | The Reference describes this as two roles: some positions *create* an obligation (`unsafe fn`, `unsafe trait`) and others *discharge* one (`unsafe {}`, `unsafe impl`). ## Why the list is kept short - **Auditing.** Undefined behaviour can only arise through one of those operations, so when memory safety breaks, the search starts at the `unsafe` blocks and the invariants they rely on. - **Small blocks.** Because the rest of the language stays checked, the advice is to keep each block to the one operation that needs it, with a comment saying why it is sound. - **Safe wrappers.** Most of std, from `Vec` to `split_at_mut`, is built on unsafe code behind safe functions, so callers never write `unsafe` themselves. - **Not "dangerous code".** An `unsafe` block is not a claim that the code is buggy; it is a claim that the author checked conditions the compiler could not. Getting one of those conditions wrong is what leads to undefined behaviour, which the lesson on undefined behaviour and Miri covers in detail.
- Does wrapping slice indexing in `unsafe { }` remove its bounds check and make it faster?No. `v[i]` inside an `unsafe` block is checked and panics exactly as outside it, and rustc warns ``unnecessary `unsafe` block`` because indexing is not an unsafe operation. To skip the check you call a different API, `slice::get_unchecked`, which is an `unsafe fn` whose precondition is that the index is in bounds.
- Is writing to a union field unsafe as well as reading one?No. The Reference makes union field access unsafe "other than to assign to it": `u.f = 1.0` compiles in safe code, while `let bits = u.i` fails with E0133, `access to union field is unsafe and requires unsafe block`. Reading assumes the stored bytes are valid for that field's type, which the compiler cannot know.
- Is every method on a raw pointer unsafe to call?No. Methods that only inspect or compute an address, such as `is_null`, `wrapping_add` and casts with `as`, are safe. Methods whose contract assumes the pointer is valid or in bounds, such as `add`, `read`, `write` and `as_ref`, are declared `unsafe fn` and need an unsafe block.
- An unsafe block turns off the borrow checker for its body.
- Code inside unsafe is not type-checked, so any cast is allowed.
- Indexing a slice inside unsafe skips the bounds check.
- Creating a raw pointer already requires an unsafe block.
- Writing unsafe means the author admits the code is buggy.