Keep the proof obligation small.
Understand what unsafe permits and what it still requires.
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.
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}");
}20
- 1
as_ptr obtains a raw pointer without dereferencing it.
- 2
The unsafe block contains the operation requiring a manual proof.
- 3
Ordinary indexing is the simpler safe choice for this example.
cargo run -p lesson_unsafe03 Mind the boundary
04 Your next build
Replace the raw-pointer read with a safe optional indexed lookup.
Reveal one possible solution +
fn main() {
let values = [10, 20, 30];
assert_eq!(values.get(1), Some(&20));
assert_eq!(values.get(10), None);
}05 Check your reasoning
Does unsafe disable all Rust safety rules?
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.