skip to content

In Rust, what does declaring an `unsafe trait` promise, and why may unsafe code trust an `unsafe impl` but not a safe trait's impl?

level: seniorimportance: should knowfreq 35%

answer

  1. the implementor signs the contract
  2. E0200 without the keyword
  3. BTreeMap cannot trust Ord
  4. blame moves to the impl

basics

~20 s

An unsafe trait says every implementation upholds a condition the compiler cannot check, signed with unsafe impl. Unsafe code may rely on that promise; a safe trait's impl may be wrong, so relying on it must never risk undefined behaviour.

solid answer

~40 s

An `unsafe trait` documents an extra condition every implementation must keep. rustc enforces the keyword both ways: a plain `impl` is E0200, and `unsafe impl` of a safe trait is E0199. Calling the trait's methods stays safe; the obligation sits with the implementor. That matters to generic unsafe code. A safe trait such as `Ord` can be implemented by anyone without `unsafe`, so `BTreeMap`'s internals must stay sound even if a key's `Ord` is not a total order; they may misbehave, never cause undefined behaviour. With an unsafe trait, unsafe code may rely on the promised property, and if an impl lies, the fault is that `unsafe impl`'s. std's stable examples are `Send`, `Sync` and `GlobalAlloc`. Use one only when a runtime check is not an option, because every implementor inherits the burden.

code

rust · 28 lines
rust
/// # Safety
/// `slot(cap)` must return a value less than `cap` for every `cap > 0`.
unsafe trait SlotPicker {
    fn slot(&self, cap: usize) -> usize;
}

struct Wrap(usize);

// SAFETY: `% cap` always yields a value below `cap` when `cap > 0`.
unsafe impl SlotPicker for Wrap {
    fn slot(&self, cap: usize) -> usize {
        self.0 % cap
    }
}

fn write_slot<P: SlotPicker>(buf: &mut [u32], picker: &P, v: u32) {
    assert!(!buf.is_empty());
    let i = picker.slot(buf.len()); // calling the method is safe
    // SAFETY: `P: SlotPicker` promises `i < buf.len()`; a wrong answer is
    // the fault of that `unsafe impl`, not of this block.
    unsafe { *buf.as_mut_ptr().add(i) = v };
}

fn main() {
    let mut buf = [0u32; 4];
    write_slot(&mut buf, &Wrap(6), 9);
    println!("{buf:?}");
}

go deeper

for a junior

Know that an unsafe trait must be implemented with unsafe impl and that Send, Sync and GlobalAlloc are std's stable examples.

for a middle

Explain that the obligation of an unsafe trait falls on implementors, unlike an unsafe fn whose obligation falls on callers, and cite E0200 and E0199.

for a senior

Argue from the BTreeMap and Ord case why generic unsafe code cannot trust a safe trait, and judge when an unsafe trait beats a runtime check.

for a principal

Weigh the cost an unsafe trait puts on every implementor against a checked safe trait or a sealed one before adding it to a public API.

## What `unsafe trait` declares An **unsafe trait** is a trait whose implementations must uphold a condition the compiler cannot check. The Reference: it "comes with extra safety conditions that must be upheld by implementations of the trait", and it "should come with documentation explaining what those extra safety conditions are". Declaring one is written `unsafe trait SlotPicker { ... }`. Three rules follow, all enforced by rustc: - **Implementing it requires `unsafe impl`.** Writing a plain `impl` fails with E0200, `the trait `SlotPicker` requires an `unsafe impl` declaration`. - **`unsafe impl` on a safe trait is also an error**: E0199, where rustc says that implementing the trait is not unsafe. The keyword must match the declaration. - **Using the trait is safe.** Calling `picker.slot(n)`, or writing a bound `P: SlotPicker`, needs no `unsafe`. Only methods declared `unsafe fn` inside the trait need an unsafe block at the call site. So the obligation lands on whoever writes the implementation, not on whoever calls the methods. That is the mirror image of an `unsafe fn`, where the obligation lands on the caller. ## Why unsafe code cannot trust a safe trait Suppose generic unsafe code relies on a trait method's answer to stay in bounds. If the trait is safe, any crate can implement it without writing `unsafe`, and a buggy or lying implementation must not be able to cause undefined behaviour, because the soundness rule says safe code can never cause undefined behaviour. The Rustonomicon's example is `BTreeMap`. It requires keys to implement `Ord`, but `Ord` is a safe trait, so the unsafe code inside `BTreeMap` must be written to survive an `Ord` implementation that is not actually a total order. Such a key makes the map behave erratically, but never unsoundly. The general rule: unsafe code may trust specific safe code it chose to depend on, but not safe code supplied by its callers through a generic parameter or a closure. ## What an unsafe trait buys An unsafe trait is the way out of that bind. With `P: SlotPicker`, the unsafe block in `write_slot` may rely on `slot` returning an index below `cap`, because every implementor signed that promise with `unsafe impl`. If an implementation breaks it, the fault lies with that `unsafe impl`, and the generic code is still sound. The code example shows the pattern; it prints `[0, 0, 9, 0]`, since `6 % 4` is 2. The standard library's stable unsafe traits illustrate the same contract: | Trait | What implementors promise | Who relies on it | |---|---|---| | `GlobalAlloc` | the allocator honours each method's contract, never touches memory that is currently allocated, and does not unwind | std's allocations, once it is registered with `#[global_allocator]` | | `Send` | the type may move to another thread | `thread::spawn` and friends | | `Sync` | `&T` may be shared between threads | `Arc`, statics | `Send` and `Sync` are the threads branch's subject; implementing them by hand for a type holding raw pointers is covered with sound safe abstractions. ## When to choose a safe trait instead Making a trait unsafe has a cost: every implementor must write `unsafe`, read the safety docs and accept blame, which pushes away users who would never touch unsafe code otherwise. Before reaching for it, weigh the alternatives: 1. **Check the answer.** `write_slot` could keep `SlotPicker` safe and use `buf[i]`, or `assert!(i < buf.len())`; one bounds check usually costs little. 2. **Make the method unsafe instead** when the condition concerns how the method is called rather than how it is implemented. 3. **Seal the trait** when only your own crate should implement it; how to seal a trait is part of the material on API evolution. 4. **Use an unsafe trait** when generic unsafe code genuinely needs to trust the implementation and a runtime check is not acceptable. ## Points interviewers probe - An unsafe trait does not make its methods unsafe to call; `unsafe fn` inside the trait does that, as with `GlobalAlloc::alloc`. - The trait's docs need a `# Safety` section, and each `unsafe impl` should carry a `// SAFETY:` comment explaining why the contract holds. - Writing `unsafe impl` is itself one of the operations only unsafe Rust permits, which is why the Book counts it among the five superpowers.

  • Does every method of an unsafe trait need an `unsafe` block at the call site?
    No. The `unsafe` on the trait puts the obligation on implementors; calling an ordinary method of it is safe, as `picker.slot(n)` is. Only a method declared `unsafe fn` inside the trait, such as `GlobalAlloc::alloc`, places an obligation on the caller as well and needs an unsafe block.
  • What should a reviewer ask of an `unsafe impl` in a pull request?
    That the trait's `# Safety` section is quoted or summarised in a `// SAFETY:` comment on the impl, and that the argument covers every input, not just the tested ones. For `SlotPicker`, the reviewer checks that `slot` returns a value below `cap` for every `cap > 0`, including after future edits to the method.

A safe trait is a stranger telling you a ladder is sturdy, so you still check it before climbing; an unsafe trait is a signed inspection certificate, so if the ladder fails, the inspector who signed is to blame.

  • Calling any method of an unsafe trait requires an unsafe block.
  • Unsafe code may rely on a correct Ord to stay sound.
  • unsafe impl can be added to any trait for extra safety.
  • An unsafe trait lets the compiler verify the contract.
  • A lying unsafe impl is the fault of the code that relied on it.