Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ DESIGN, SAFETY & SHIPPING
BUILD NOTE 50 / 53

Keep the proof obligation small.

Understand what unsafe permits and what it still requires.

BY NAVAN SAMI◷ 9 MIN READADVANCEDRUST 2024

01 Understand the contract

unsafe enables specific operations such as dereferencing raw pointers or calling unsafe functions. It does not turn off the type system, ownership rules for ordinary references, or the need to uphold memory safety. The programmer must establish validity, alignment, lifetime, and aliasing requirements that the compiler cannot prove. Prefer a safe standard-library operation when one exists. When writing a safe wrapper around unsafe internals, document the invariant and test boundaries, while recognizing tests alone cannot prove absence of undefined behavior.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/unsafe/src/main.rs
fn main() {
    let values = [10, 20, 30];
    let pointer = values.as_ptr();
    // SAFETY: pointer comes from a live array; index 1 is in bounds,
    // properly aligned, and no mutation conflicts with this read.
    let second = unsafe { *pointer.add(1) };
    assert_eq!(second, values[1]);
    println!("{second}");
}
↳ EXPECTED OUTPUT
20
  1. 1

    as_ptr obtains a raw pointer without dereferencing it.

  2. 2

    The unsafe block contains the operation requiring a manual proof.

  3. 3

    Ordinary indexing is the simpler safe choice for this example.

From the extracted rust-workbench folder
cargo run -p lesson_unsafe

03 Mind the boundary

04 Your next build

A SMALL MISSION

Replace the raw-pointer read with a safe optional indexed lookup.

Reveal one possible solution +
solutions/unsafe/src/main.rs
fn main() {
    let values = [10, 20, 30];
    assert_eq!(values.get(1), Some(&20));
    assert_eq!(values.get(10), None);
}

05 Check your reasoning

QUICK SIGNAL CHECK

Does unsafe disable all Rust safety rules?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.