Unsafe Rust for FFI and low-level optimizations

Marcus Chen Jan 2026
1 tab
extern "C" {
    fn abs(input: i32) -> i32;
}

pub fn safe_abs(input: i32) -> i32 {
    unsafe { abs(input) }
}

fn main() {
    println!("abs(-42) = {}", safe_abs(-42));
}
1 file · rust Explain with highlit

Unsafe Rust lets you bypass some of the compiler's safety checks when necessary. Common uses include FFI (calling C code), dereferencing raw pointers, and implementing low-level data structures. The unsafe keyword creates a boundary where you promise the code is safe. I minimize unsafe code and encapsulate it in safe APIs. For FFI, I declare external functions with extern "C" and wrap them in safe Rust functions that validate inputs. Unsafe is also used for performance: bypassing bounds checks in tight loops (.get_unchecked()). The key is to isolate unsafe blocks, document invariants, and test thoroughly. When used correctly, unsafe enables zero-cost abstractions that aren't possible in safe Rust.