Systems Design Questions · 19 min · free with an account

Reasoning About unsafe

Lesson preview · about 30%

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

Core idea

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

Start with the idea

It permits exactly five operations 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 dereferencing. 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?

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Rust Interview Prep