Chapter 25: Unsafe Rust

Rust is widely recognized for its strong safety guarantees. By leveraging compile-time static analysis and runtime checks (such as array bounds checking), it prevents many common memory and concurrency bugs. However, Rust’s static analysis is conservative—it may reject code that is actually safe if it cannot prove that all invariants are met. Moreover, hardware itself is inherently unsafe, and low-level systems programming often requires direct hardware interaction. To support such programming while preserving as much safety as possible, Rust provides Unsafe Rust.

Unsafe Rust is not a separate language but an extension of safe Rust. It grants access to certain operations that safe Rust disallows. In exchange for this power, you must manually uphold Rust’s core safety invariants. Many parts of the standard library, such as slice manipulation functions, vector internals, and thread and I/O management, are implemented as safe abstractions over underlying unsafe code. This pattern—isolating unsafe code behind a safe API—is crucial for preserving overall program safety.