Answer#
Most application code never needs unsafe. A crate-level lint turns that into a guarantee the compiler checks:
#![forbid(unsafe_code)]
fn main() {
let v = [1u8, 2, 3];
let x = unsafe { *v.get_unchecked(1) };
println!("{x}");
}forbid is stronger than deny: an inner #[allow(unsafe_code)] cannot lift it. Compiling the program above with rustc --edition 2021 fails:
error: usage of an `unsafe` block
--> f1.rs:5:13
|
5 | let x = unsafe { *v.get_unchecked(1) };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
note: the lint level is defined here
--> f1.rs:1:11
|
1 | #![forbid(unsafe_code)]
| ^^^^^^^^^^^
error: aborting due to 1 previous error(This forbids unsafe code in your crate. Dependencies and the standard library still contain unsafe; the lint says nothing about them.)
Where unsafe is needed#
Calling into C, working with raw pointers or implementing a low-level data structure needs unsafe. Keep it contained:
- Put it in one small module, with a safe public interface that cannot be misused.
- Write a
# Safetysection on everyunsafe fn, stating what the caller must guarantee. - Write a
// SAFETY:comment on everyunsafeblock, stating why the conditions hold here (see the next thread). - Turn on the lint
unsafe_op_in_unsafe_fn. In edition 2021 it is allowed by default, which means the body of anunsafe fncounts as one big unsafe block; in edition 2024 it warns by default (the compiler output on the program below, built with--edition 2024, beginswarning[E0133]). With the lint set to deny, each unsafe operation must sit in its own block:
error[E0133]: dereference of raw pointer is unsafe and requires unsafe block
--> f2.rs:2:5
|
2 | *p
| ^^ dereference of raw pointer
|
= note: raw pointers may be null, dangling or unaligned; they can violate aliasing rules and cause data races: all of these are undefined behavior
note: an unsafe function restricts its caller, but its body is safe by default
--> f2.rs:1:1
|
1 | unsafe fn first(p: *const u8) -> u8 {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
= note: requested on the command line with `-D unsafe-op-in-unsafe-fn`(Shortened: one note line removed. Produced by rustc --edition 2021 -D unsafe_op_in_unsafe_fn on a function with a bare *p in an unsafe fn.)
The corrected program compiles and runs, and prints 7:
#![forbid(unsafe_op_in_unsafe_fn)]
/// # Safety
/// `p` must be non-null, aligned, and point to a live `u8`.
unsafe fn first(p: *const u8) -> u8 {
// SAFETY: the caller guarantees the pointer is valid (see the contract above).
unsafe { *p }
}
fn main() {
let v = [7u8];
// SAFETY: `v.as_ptr()` points to the first element of a live, non-empty array.
println!("{}", unsafe { first(v.as_ptr()) });
}Common mistakes#
- Using
unsafeto silence a borrow-checker error. Restructure the code instead. - Putting a large block under one
unsafeso that nobody can see which line needs it. - Writing a safe function that can cause undefined behaviour when called with bad input: if callers can break the rules, the function must be
unsafeor must check.
Related questions#
Can I count the unsafe code in my dependencies?#
Tools such as cargo geiger exist for that. Check its documentation; a count is a hint where to look, not a verdict.
Does forbid(unsafe_code) make a crate memory safe?#
It removes unsafe code from that crate. The crate is only as safe as the unsafe code in its dependencies and the standard library, which are widely used but not immune to bugs.
Sources#
- The Rust Reference, "Unsafe blocks and functions": https://doc.rust-lang.org/reference/unsafe-keyword.html
- The Rust Reference, lint levels (
forbid): https://doc.rust-lang.org/rustc/lints/levels.html - Rust Edition Guide, "unsafe_op_in_unsafe_fn": https://doc.rust-lang.org/edition-guide/rust-2024/unsafe-op-in-unsafe-fn.html