Systems Design Questions · 19 min · free lesson

Reasoning About unsafe

unsafe is a claim about an invariant, not a disabled checker.

Core idea

unsafe moves the obligation to you; it never removes it.

Lesson map: an is_empty check guarding get_unchecked(0) with a SAFETY comment, above the rule that unsafe moves the obligation to you.
The check establishes bounds for this access. values.first().copied() is a simpler safe alternative; unsafe does not disable borrowing or type checking.

Understand it

unsafe permits a short list of operations the compiler cannot check and leaves the borrow checker fully in force. A sound abstraction documents the invariant its unsafe block relies on and enforces it in the safe API, so no safe caller can ever trigger undefined behaviour.

unsafe permits operations whose preconditions the compiler cannot fully verify. It is not a switch that disables ordinary type checking and borrowing rules. A sound wrapper exposes a safe API only if every safe caller input preserves the assumptions used by its internal unsafe operations. For example, a helper that reads the first slice element with get_unchecked(0) must ensure the slice is nonempty before calling it, because an out-of-bounds call is already undefined behaviour. A safe slice.first() is usually simpler and may optimize just as well.

Explain the proof obligation as four questions: what must be true, where is it established, how long does it remain true, and can a safe caller make it false? For raw pointers, that may include validity, alignment, initialization, bounds, provenance, and aliasing. For FFI, it also includes the foreign function's actual signature and ownership contract. A passing test cannot prove that undefined behavior is absent, so keep the unsafe block small and the invariant close.

Avoid a common interview trap: listing only the syntax categories without explaining why they need a proof. It is valuable to know the permitted operations, but the stronger answer is an example of a safety invariant and how a wrapper enforces it. Mention code review, Miri or sanitizers as useful evidence where applicable, while making clear that tooling complements reasoning rather than replacing it.

An unsafe function shifts some preconditions to its caller; a safe wrapper retains responsibility for enforcing them itself. Distinguish those two API shapes. A SAFETY comment at the call site should explain why the preconditions hold there, while the unsafe function documentation must state them precisely.

Interview follow-up: Show the safe alternative, then explain why tests and Miri provide evidence rather than a general proof of soundness.

Read the code

fn first(values: &[u8]) -> Option<u8> {
    if values.is_empty() { return None; }
    // SAFETY: the nonempty check proves index 0 is in bounds.
    Some(unsafe { *values.get_unchecked(0) })
}
fn main() { assert_eq!(first(&[]), None); }

The check establishes bounds for this access. values.first().copied() is a simpler safe alternative; unsafe does not disable borrowing or type checking.

Practise this code in Playground ↗

Try it

Review a small unsafe wrapper and list every invariant its safe API protects.

What success looks like: Safe callers cannot reach undefined behaviour by any input.

Check your understanding

What must a safe wrapper establish before this unchecked access?

Reveal the answer
  1. Writing unsafe transfers every correctness obligation to the compiler.
  2. Every safe call must preserve the preconditions of the internal unsafe operation.
  3. A successful test removes the need to justify the unchecked index.

The check establishes bounds for this access. values.first().copied() is a simpler safe alternative; unsafe does not disable borrowing or type checking.

Go deeper

Common misconception: A successful test removes the need to justify the unchecked index.

A test covers only the inputs it ran, and undefined behaviour need not fail visibly. The justification is the is_empty check, which holds for every safe call.

  1. Identify the contract: unsafe is a claim about an invariant, not a disabled checker.
  2. Trace the concrete example: The invariant is checked, then written down beside the block.
  3. Test the changed constraint: Show the safe alternative, then explain why tests and Miri provide evidence rather than a general proof of soundness.

Transfer challenge: Show the safe alternative, then explain why tests and Miri provide evidence rather than a general proof of soundness.

Connections

  • dyn Trait vs Generics: Dispatch and code size tradeoffs
  • Atomics and Ordering: Relaxed, Acquire/Release, SeqCst
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Reasoning About unsafe (courseId "interview", lessonId "q-unsafe")
Link: https://crabrix.com/learn/interview/q-unsafe/
Goal: unsafe moves the obligation to you; it never removes it.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=interview/q-unsafe) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.