Systems Rust · 21 min · free with an account

unsafe Rust

Lesson preview · about 30%

unsafe unlocks five operations; it does not turn off the borrow checker.

Core idea

unsafe is a claim about an invariant, not permission to skip the rules.

Start with the idea

Inside an unsafe block you may dereference a raw pointer, call an unsafe function, access a mutable static, implement an unsafe trait, and read a union field. Everything else is checked exactly as before. The block is a promise that you have verified an invariant the compiler cannot, which is why the convention is to write that invariant down as a SAFETY comment.

An unsafe block permits a small set of operations whose safety conditions cannot be fully checked by the compiler. It does not relax ordinary borrowing rules for safe references or make a wrong pointer valid. The lesson's get_unchecked(0) example is safe only because the slice is known to contain index zero at that exact call site. The SAFETY comment should connect the preceding check to the API's precondition. If a future edit changes that control flow, the proof must be reviewed again.

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 Macros & Systems Rust