# How do I keep unsafe code out of my crate, or contain it where it is needed?
Source: https://ruststudio.org/community/t/107/how-do-i-keep-unsafe-code-out-of-my-crate-or-contain-it-where-it-is-needed
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0, Windows 11
Category: Help and questions | Kind: FAQ | Tags: security, unsafe, lints | Views: 0

## Short answer
Put #![forbid(unsafe_code)] in a crate that does not need unsafe and the compiler rejects any unsafe block. Where unsafe is needed, isolate it in a small module, document the caller's duties in a Safety section, and deny unsafe_op_in_unsafe_fn so each unsafe operation sits in its own block.

## Answer
## Answer
Most application code never needs `unsafe`. A crate-level lint turns that into a guarantee the compiler checks:

```rust title=src/main.rs
#![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:

```text
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:

1. Put it in one small module, with a safe public interface that cannot be misused.
2. Write a `# Safety` section on every `unsafe fn`, stating what the caller must guarantee.
3. Write a `// SAFETY:` comment on every `unsafe` block, stating why the conditions hold **here** (see the next thread).
4. Turn on the lint `unsafe_op_in_unsafe_fn`. In edition 2021 it is allowed by default, which means the body of an `unsafe fn` counts as one big unsafe block; in edition 2024 it warns by default (the compiler output on the program below, built with `--edition 2024`, begins `warning[E0133]`). With the lint set to deny, each unsafe operation must sit in its own block:

```text
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`:

```rust title=src/main.rs
#![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 `unsafe` to silence a borrow-checker error. Restructure the code instead.
- Putting a large block under one `unsafe` so 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 `unsafe` or 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
