
Understand it
unsafe unlocks five powers. Inside an unsafe block you may dereference a raw pointer, call an unsafe function, access a mutable static, and read a union field; the fifth, implementing an unsafe trait, is an unsafe impl item, not something a block grants. 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.
Prefer a safe operation when its cost is negligible or the optimizer can remove the check; slice.first().copied() is clearer here. Use unsafe only when a concrete boundary requires it, and make the boundary as small as possible. A safe wrapper around unsafe internals owes callers a sound contract for every input it accepts. Test edge cases such as empty slices, but remember tests cannot prove absence of undefined behavior. Audit aliasing, lifetimes, alignment, initialization, and thread interaction as applicable. Ask: what invariant is required, who establishes it, when can it stop holding, and can safe callers break it? That proof is the work behind the keyword, not an optional comment after the implementation.
A SAFETY comment should survive code review as an argument, not a ritual phrase. If the proof depends on a length check, keep that check close; if it depends on another module, link the invariant clearly. Revisit the comment whenever data ownership or concurrency changes. Reducing unsafe code to one audited helper often makes the rest of the program both faster to review and safer to extend. The test is whether safe callers can violate the claimed invariant.
Read the code
fn first(slice: &[u32]) -> Option<u32> {
if slice.is_empty() {
return None;
}
// SAFETY: the check above guarantees
// that index 0 exists.
Some(unsafe { *slice.get_unchecked(0) })
}A small block, and the reason it is sound written next to it.
Practice starter
let value = unsafe { *pointer };Try it
Wrap an unchecked operation in a safe API that cannot be misused.
What success looks like: No safe caller can trigger undefined behaviour.
Check your understanding
What must be true for that to be sound?
Reveal the answer
- Nothing — unsafe makes any dereference legal
- The pointer is non-null, aligned, and points at a live, initialised value
- The pointer has to be declared mut before it is dereferenced
unsafe moves the obligation to you; it does not remove it.
Go deeper
Common misconception: “unsafe makes any dereference legal, so nothing else has to hold.”
unsafe is a claim about an invariant, not permission to skip the rules. The pointer must still be valid, aligned, and point at a live, initialised value.
- Check the input:
slice.is_empty()returns early withNone, so below that line the slice has at least one element. - Read the proof: The
SAFETYcomment names that check, becauseget_unchecked(0)requires index 0 to be in bounds and does not test it. - Test the boundary:
first(&[])givesNoneandfirst(&[5])givesSome(5). Both are safe calls, and no input reaches the read without the check.
Transfer challenge: Delete the is_empty check and find the input that now breaks the proof. Restore it, replace the block with slice.first().copied(), and say whether anything was lost.
Connections
- cfg & Features: Compiling different code per target
- FFI: extern "C", repr(C), and raw pointers
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: unsafe Rust (courseId "systems", lessonId "unsafe") Link: https://crabrix.com/learn/systems/unsafe/ Goal: unsafe is a claim about an invariant, not permission to skip the rules. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=systems/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.