Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Unsafe Snippets

This chapter isolates unsafe Rust and FFI snippets so the invariant-carrying parts of the language can be reviewed directly.

Mental Model

  • unsafe does not mean "turn checks off."
  • unsafe means the compiler is trusting the engineer to uphold extra invariants.
  • Unsafe code is about precise boundaries and explicit responsibility.

Raw pointers

fn main() {
    let mut x = 5;
    let p1 = &x as *const i32;
    let p2 = &mut x as *mut i32;

    unsafe {
        println!("{}", *p1);
        *p2 = 10;
    }
}

Unsafe function

#![allow(unused)]
fn main() {
unsafe fn read_ptr(ptr: *const i32) -> i32 {
    *ptr
}
}

Safe wrapper around unsafe

#![allow(unused)]
fn main() {
fn first_byte(slice: &[u8]) -> Option<u8> {
    if slice.is_empty() {
        None
    } else {
        unsafe { Some(*slice.as_ptr()) }
    }
}
}

FFI declaration

unsafe extern "C" {
    fn abs(input: i32) -> i32;
}

fn main() {
    unsafe {
        println!("{}", abs(-3));
    }
}

Unsafe mental model

#![allow(unused)]
fn main() {
// unsafe does not mean "turn checks off"
// unsafe means "the compiler is trusting me to uphold extra invariants"
}

Unsafe Recall Checklist

  • Can I explain what unsafe actually means?
  • Can I explain which invariants are now my responsibility?
  • Can I explain how to keep unsafe blocks small?
  • Can I explain the value of safe wrappers around unsafe internals?
  • Can I explain the basics of extern "C" and FFI boundaries?