liveBook · Manning

Unsafe block

As explained in Learn Rust in a Month of Lunches

An unsafe block is a Rust code block that permits operations requiring the programmer to uphold safety invariants that the compiler cannot verify.

An unsafe block marks code where Rust cannot verify every safety guarantee. It does not automatically make the code wrong; it signals that the programmer must uphold the missing safety invariants. section 16.4.1

Rust requires an unsafe block when calling an unsafe function. The compiler first rejects the call, then accepts it after the call is placed inside an explicitly marked block. section 16.4.1

Use unsafe blocks sparingly and understand what responsibility they introduce:

  • Use them for low-level system resources, foreign-language functions such as libc bindings, unsafe functions, and mutable statics. section 16.4.1 section 16.6
  • Treat the block as a deliberate trust boundary: the compiler permits operations it could not otherwise verify, while the programmer must prevent undefined behavior. section 16.4.1 section 16.4.2

Mutable static and data races

A mutable static can be changed or printed only inside an unsafe block. That permission does not make concurrent access safe: multiple threads incrementing the same value can produce inconsistent results because aliasing violations or data races cause undefined behavior. section 16.4.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains the safety boundary and compiler corrections, then demonstrates data races without developing unsafe-code internals.
Examples
Demonstrates an unsafe function call and concurrent increments of a mutable static producing inconsistent totals.
What it assumes
Assumes basic Rust function and threading syntax, while teaching why unsafe operations require explicit compiler-visible boundaries.
What you can do after
Apply unsafe blocks to call unsafe functions and access mutable statics while recognizing the responsibility for preventing undefined behavior.
How it connects
Connects unsafe blocks with unsafe functions, foreign-function interfaces, mutable statics, data races, and undefined behavior.

Also explained in

Compare how 3 books explain unsafe block →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.