Unsafe traits and invariants
Quick answer
An unsafe trait makes implementers responsible for a safety contract that other code may rely on. An unsafe impl is an assertion that the contract holds for that type.
Specify the implementer obligation
Send and Sync are familiar unsafe traits governing cross-thread transfer and shared references. Prefer compiler-derived implementations when available. The custom trait below is only a teaching contract: its method is safe but implementers must always return an index below two. The safe consumer relies on that requirement for unchecked indexing. A faulty unsafe impl could make that consumer unsound.
/// # Safety/// index() must always return 0 or 1 for every call.unsafe trait PairIndex { fn index(&self) -> usize; }struct Second;// SAFETY: Second always returns 1, which is below 2.unsafe impl PairIndex for Second { fn index(&self) -> usize { 1 } }fn select(p: &impl PairIndex) -> u32 { let data = [11, 22]; // SAFETY: PairIndex contract ensures the index is in bounds. unsafe { *data.get_unchecked(p.index()) }}fn main() { println!("{}", select(&Second)); }Expected stdout (not executed):
22The implementation and the consumer have complementary obligations. Normal checked indexing would be simpler here.
unsafe trait Marker {}struct Item;impl Marker for Item {}fn main() {}Expected: compilation fails; exact diagnostic not verified.
This compile-fail example has no executable unsafe access.
Common mistake
Do not manually implement Send or Sync just to satisfy a thread API; prove the actual thread-safety invariants first.
Try it yourself
Write the safety contract for an index constrained to three elements and explain why an incorrect unsafe impl would break it.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Unsafe traits and invariants — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A custom unsafe trait promises index() always returns 0 or 1. An implementation returns 2. What is the consequence?
Unsafe traits and invariants — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust /// # Safety /// index() must always return 0 or 1 for every call. unsafe trait PairIndex { fn index(&self) -> usize; } struct Second; // SAFETY: Second always returns 1, which is below 2. unsafe impl PairIndex for Second { fn index(&self) -> usize { 1 } } fn select(p: &impl PairIndex) -> u32 { let data = [11, 22]; // SAFETY: PairIndex contract ensures the index is in bounds. unsafe { *data.get_unchecked(p.index()) } } fn main() { println!("{}", select(&Second)); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Unsafe traits and invariants — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust unsafe trait Marker {} struct Item; impl Marker for Item {} fn main() {} ``` Which outcome or interpretation best matches this example?