What is unsafe Rust and what does it allow?
Answer
Unsafe Rust is a subset of Rust inside unsafe { } blocks that allows five additional capabilities not permitted in safe Rust: 1) Dereference raw pointers (*const T, *mut T). 2) Call unsafe functions or methods. 3) Access or modify mutable static variables. 4) Implement unsafe traits. 5) Access fields of union types. Unsafe does NOT disable the borrow checker — it merely allows these additional operations. The programmer must manually uphold safety invariants within unsafe blocks. The goal is to contain unsafety: you write a small unsafe abstraction and expose a safe public API. For example, Vec uses unsafe internally but is safe to use. Never write unsafe code unless you fully understand the invariants required.
Previous
How does unit testing and integration testing work in Rust?
Next
What is the difference between procedural macros and declarative macros in Rust?
More Rust Questions
View all →- Intermediate How does error handling with the ? operator work in Rust?
- Intermediate What are the thiserror and anyhow crates for error handling?
- Intermediate What are trait objects (dyn Trait) in Rust?
- Intermediate What are generics in Rust and how do where clauses work?
- Intermediate What are Rust smart pointers?