expression

Define and implement an unsafe trait

An unsafe trait places extra requirements on implementers, not automatically on callers of its safe methods. The example uses a deliberately narrow educational contract: offset zero is readable through a returned pointer while self is borrowed. The safe consumer relies on that requirement. Prefer returning a reference for real APIs when possible. Expected stdout (not executed): 23 Common mistake: Providing an unsafe impl without proving its entire contract, or assuming safe methods need an unsafe call.

Formal Syntax & Structure

rust syntaxrust
unsafe trait Contract { ... } / unsafe impl Contract for Type { ... }

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    /// # Safety    /// ptr must be non-null, aligned and valid for reading an initialized    /// i32 while self is shared-borrowed; no conflicting writes may occur.    unsafe trait Readable {        fn ptr(&self) -> *const i32;    }    struct Number(i32);    // SAFETY: the returned pointer refers to self.0, a live i32;    // a shared borrow prevents conflicting writes through safe code.    unsafe impl Readable for Number {        fn ptr(&self) -> *const i32 { &self.0 }    }    fn read(value: &impl Readable) -> i32 {        // SAFETY: the unsafe trait promises validity during this borrow.        unsafe { *value.ptr() }    }    println!("{}", read(&Number(23)));}
Rust Reference