expression

Check a precondition at a safe abstraction boundary

A safe wrapper must enforce the requirements of every unsafe operation for every input allowed by its public interface. This teaching example bounds-checks a slice index before invoking get_unchecked. Prefer slice.get in actual code; the purpose here is to make the boundary explicit. Expected stdout (not executed): 7 Common mistake: Using debug_assert for a safety requirement that must hold in optimized builds.

Formal Syntax & Structure

rust syntaxrust
if index < items.len() { unsafe { ... } }

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    fn checked(items: &[i32], index: usize) -> Option<&i32> {        if index >= items.len() { return None; }        // SAFETY: index < len, and the shared slice supplies        // initialized elements valid for the returned borrow.        Some(unsafe { items.get_unchecked(index) })    }    assert_eq!(checked(&[], 0), None);    assert_eq!(checked(&[7], usize::MAX), None);    println!("{}", checked(&[7], 0).unwrap());}
Rust Reference