Unsafe Rust permits certain operations whose safety the compiler cannot guarantee. An `unsafe` block tells the compiler to allow those operations, but it also makes the programmer responsible for meeting their safety requirements. The keyword does not mean that the code is necessarily wrong. section 16.4.1
Unsafe operations are useful when working with hardware memory addresses or calling functions in another language. Many Rust programs never need them. section 16.4.1
An unsafe function must be called from an unsafe context. This example declares an unsafe function but calls it without an unsafe block: section 16.4.1
unsafe fn uh_oh() {}
fn main() {
uh_oh();
}
The call to `uh_oh()` is outside an unsafe block. section 16.4.1
The compiler reports error E0133: the call requires an unsafe function or block. One correction is to wrap the call in an unsafe block: section 16.4.1
unsafe fn uh_oh() {}
fn main() {
unsafe {
uh_oh();
}
}
The block marks the call as an operation for which the programmer accepts responsibility. section 16.4.1
A mutable static, declared with `static mut`, is another case requiring unsafe access. Multiple threads can change it, and overlapping access can cause a data race and undefined behavior. Undefined behavior is not fixed by adding `unsafe`: the block permits the operation but does not make it safe. section 16.4 section 16.4.2
Unchecked unwrapping
`Option::unwrap_unchecked()` assumes the value is `Some`. Calling it on `None` causes undefined behavior. A safety comment can explain why the assumption holds, but unchecked methods are not guaranteed to be faster than checked alternatives. section 16.4.4
fn main() {
let my_option = Some(10);
// SAFETY: my_option is declared as Some(10). It will never be None
let unwrapped = unsafe {
my_option.unwrap_unchecked()
};
println!("{unwrapped}");
}
The comment records why this particular unchecked unwrap is safe: the value is known to be `Some(10)`. section 16.4.4
When in doubt, prefer a safe alternative. Use unsafe operations only when you can establish the conditions they require. section 16.4.4



