
Understand it
An unsafe trait means incorrect implementation can cause undefined behavior in code that trusts it. Document every invariant precisely and keep the unsafe impl beside evidence that it holds.
An unsafe trait is a promise whose incorrect implementation can invalidate assumptions made by other code. Its documentation must state the invariant precisely: which operations, lifetimes, alignment, or thread interactions are safe, and what every implementor must maintain. The unsafe keyword on the impl means the implementor has checked that contract; it is not a compiler proof. A generic caller may rely on the trait bound and therefore cannot recheck each concrete implementation.
Avoid vague contracts such as “instances never expose moves” unless the type truly enforces that property. A plain FixedBuffer can be moved between bindings, so claiming stable address for it would be unsound. For a learning example, use a narrow contract instead, as ZeroIsValid does: the all-zero bit pattern must be a valid value of the type. The standard Send is another precise contract: a type may be transferred to another thread only when doing so cannot cause a data race or invalid access. Examine every field before adding an unsafe impl; a non-atomic shared pointer can break that claim. Prefer safe auto traits and existing library abstractions wherever possible. If you must author an unsafe trait, write a safety section with concrete counterexamples, place each impl beside its proof, and review changes to the type's internals against that proof.
The teaching trait example has no consumer that relies on the promise, so it illustrates syntax rather than proving a real unsafe abstraction. In production, state exactly what unsafe generic code may assume from the bound. Then try to construct a counterexample type and see whether the proposed contract rules it out. If the contract cannot be written precisely, the trait is not ready to publish.
Read the code
/// # Safety
/// The all-zero bit pattern must be a valid Self value.
unsafe trait ZeroIsValid {}
#[repr(transparent)]
struct Byte(u8);
// SAFETY: every u8 bit pattern is valid, including zero.
unsafe impl ZeroIsValid for Byte {}A narrow contract makes the implementor's proof concrete: zero is a valid u8 and therefore a valid Byte.
Practice starter
unsafe trait StableAddress {}
struct FixedBuffer([u8; 16]);
// Counterexample: this claim is false, as a FixedBuffer can be moved.
// SAFETY: instances never expose moves.
unsafe impl StableAddress for FixedBuffer {}Try it
Compare the example's proof with this SAFETY comment. Move a FixedBuffer between two bindings, print its address before and after, and say which claim fails.
What success looks like: You can say why ZeroIsValid for Byte holds and why StableAddress for FixedBuffer is unsound.
Check your understanding
Why must that StableAddress impl be written unsafe?
Reveal the answer
- Callers rely on its promise
- Traits are never checked
- Its struct holds an array
Unsafe code may rely on the trait's promise without rechecking it. The keyword marks the implementor's claim, and the compiler accepts it even though this one is false.
Go deeper
Common misconception: “Writing unsafe impl proves that the trait's invariant holds.”
An unsafe trait defines a safety contract. An implementor must prove its type preserves that contract for every safe caller; merely writing unsafe impl does not establish the invariant.
- Read the contract: The
# Safetysection states the one promise: the all-zero bit pattern must be a valid value of the implementing type. - Check the implementor:
Byteisrepr(transparent)overu8, and zero is a validu8, so theSAFETYcomment proves the promise forByte. - Find who relies on it: Nothing calls the trait here. Generic
unsafecode bounded byT: ZeroIsValidcould create a zeroedTand rely on the implementor's proof.
Transfer challenge: Write a generic fn zeroed<T: ZeroIsValid>() -> T using std::mem::zeroed. Then name a type for which an unsafe impl would be false, such as a struct holding &u8, and say where undefined behaviour would appear.
Connections
- Representation & Layout: Make a data layout contract explicit at a boundary
- Benchmark & Profile: Find the real bottleneck before optimizing
Learn this lesson with AI
Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.
I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools. Lesson: Unsafe Traits (courseId "systems", lessonId "unsafe-traits") Link: https://crabrix.com/learn/systems/unsafe-traits/ Goal: An unsafe trait means incorrect implementation can cause undefined behavior in code that trusts it. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=systems/unsafe-traits) and I will write the code there. Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.