Interacting with Unsafe Rust
Understand when and how to use `unsafe` blocks to bypass Rust's safety checks, enabling FFI and low-level memory operations.
Unsafe Rust: An Introduction
Welcome to Unsafe Rust! While Rust is famous for its memory safety guarantees, there are specific scenarios where you might need to bypass some of these checks.
The unsafe keyword in Rust allows you to do just that. It's not a way to write 'bad' code, but rather a tool for advanced use cases where you need more direct control over memory or hardware.
The Five Unsafe Superpowers
When you use an unsafe block, you gain access to five special actions that the Rust compiler normally prevents:
- Dereference raw pointers: Directly access memory addresses.
- Call
unsafefunctions or methods: Execute functions with preconditions the compiler can't verify. - Implement
unsafetraits: Declare that your type upholds specific invariants. - Access or modify mutable static variables: Share mutable state globally, risking data races.
- Access fields of
unions: Read from a union, which might be an invalid type for the current data.
All lessons in this course
- Declarative Macros (`macro_rules!`)
- Procedural Macros: Derive, Function
- Interacting with Unsafe Rust