thecodex.expert · The Codex Family of Knowledge
Rust

Unsafe Rust

unsafe does not disable Rust’s safety checks — it unlocks exactly five specific operations the compiler cannot verify on its own, and every other rule still fully applies.

Rust 1.96 5 specific powers Last verified:
Canonical Definition

An unsafe block unlocks exactly five capabilities: dereferencing a raw pointer, calling an unsafe function, accessing or mutating a mutable static variable, implementing an unsafe trait, and accessing a union's fields. It is a common misconception that unsafe turns off the borrow checker or other safety checks entirely — it does not; those rules still apply everywhere. unsafe simply means the programmer is manually vouching for a small number of specific invariants the compiler cannot verify by itself.

Dereferencing a raw pointer

Raw pointers (*const T, *mut T) can be created safely, but dereferencing one — the actual read or write — requires unsafe, since the compiler cannot verify the pointer is valid.

Rustraw_pointers.rs
let mut num = 5;
let r1 = &num as *const i32;   // creating a raw pointer: SAFE
let r2 = &mut num as *mut i32;

unsafe {
    println!("{}", *r1);   // dereferencing: requires unsafe
    *r2 = 10;
}

Calling an unsafe function

A function marked unsafe fn can only be called from inside an unsafe block — the keyword documents that the function has invariants the caller must uphold that the compiler cannot check.

Rustunsafe_fn.rs
unsafe fn dangerous() {
    println!("doing something the compiler can't verify");
}

unsafe {
    dangerous();   // must be called from within unsafe
}

The other three: statics, unsafe traits, unions

Mutable static variables require unsafe to read or write, since multiple threads accessing one could race. Implementing an unsafe trait (like Send or Sync manually) requires unsafe because the implementer is promising an invariant the compiler cannot check. Accessing a union's field requires unsafe because the compiler cannot know which field is currently valid. In every case, safe Rust code is typically wrapped around the unsafe operations, exposing a safe public API while the unsafe details stay internal — this is exactly how much of the standard library itself, like Vec, is implemented.

Sources

1
The Rust Project. The Rust Programming Language, "Unsafe Rust", doc.rust-lang.org/book/ch19-01.