Academy
Safe Wrappers and Null Safety: Building Safe APIs Over Raw Pointers with Option<&T>
Discover how Rust tames pointers with references, safe wrappers, and Option<&T> to eliminate memory safety bugs while keeping systems programming power.
6 menit baca
Di halaman ini
If you've programmed in C, you have a relationship with pointers that's somewhere between Stockholm syndrome and genuine affection. Pointers are powerful. Pointers are flexible. Pointers are also responsible for approximately 70% of all security vulnerabilities in systems software, according to Microsoft, Google, and the NSA. Null pointer dereferences, dangling pointers, buffer overflows, use-after-free—the entire rogues' gallery of memory safety bugs traces back to one fundamental problem: pointers let you do anything, including things you shouldn't.
Rust didn't eliminate pointers. It tamed them. Rust's reference system (&T and &mut T) provides everything you need from pointers—indirection, borrowing, efficient parameter passing—with compile-time guarantees that the reference is non-null, properly aligned, pointing to valid data, and not creating data races. For the 99% of code that needs pointer-like behavior, references are strictly better than raw pointers: same performance, vastly more safety, zero runtime cost for the guarantees.
For the remaining 1%—FFI with C libraries, implementing custom allocators, building lock-free data structures—Rust provides raw pointers (*const T and *mut T) that work like C pointers. But they're quarantined behind the unsafe keyword, making every use visible, auditable, and reviewable. You can't accidentally use a raw pointer; you have to deliberately opt into the unsafety.
At RantAI, references are our primary tool for data access across function boundaries, module boundaries, and (with Arc) thread boundaries. Raw pointers appear only in our FFI layer, isolated behind safe wrappers. This article, drawn from Chapter 10 of our guide "The Rust Programming Language," covers the full spectrum from safe references to raw pointers.
References: Safe Pointers#
fn sum(data: &[i32]) -> i32 {
data.iter().sum()
}
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
let total = sum(&numbers); // Pass a reference — no copy, no move
println!("Sum: {}, still have numbers: {:?}", total, numbers);
}
A reference is a pointer with four compile-time guarantees:
Non-null. There is no null reference in Rust. If you need "maybe no value," use Option<&T>, which makes the absence explicit in the type system.
Valid. A reference always points to live, initialized data of the correct type. The lifetime system proves this at compile time.
Aligned. References always point to properly aligned data. Misaligned access (which causes crashes on some architectures) is structurally impossible.
Non-aliasing (for &mut T). A mutable reference guarantees exclusive access—no other reference to the same data can exist simultaneously.
// These guarantees are FREE — zero runtime cost
fn process(data: &Vec<String>) {
// data is guaranteed non-null — no null check needed
// data is guaranteed valid — no validity check needed
// data is guaranteed aligned — no alignment check needed
// data is guaranteed not to be modified by other code — no lock needed
for item in data {
println!("{}", item);
}
}
The Safety Spectrum#
fn main() {
let x = 42;
// SAFEST: Immutable reference — read-only, shareable
let r1: &i32 = &x;
let r2: &i32 = &x; // Multiple immutable refs OK
let mut y = 42;
// SAFE: Mutable reference — exclusive read-write access
let r3: &mut i32 = &mut y;
*r3 += 1; // Modification through exclusive reference
// UNSAFE: Raw pointers — C-like, no guarantees
let raw_const: *const i32 = &x; // Creating raw ptr is safe
let raw_mut: *mut i32 = &mut y; // Creating raw ptr is safe
unsafe {
// DEREFERENCING raw pointers requires unsafe
println!("raw const: {}", *raw_const);
*raw_mut = 100;
}
}
The spectrum goes: &T (safest, multiple readers) → &mut T (safe, exclusive writer) → *const T / *mut T (unsafe, C-like). Each step down trades safety guarantees for flexibility. The compiler enforces that you acknowledge the trade-off with unsafe.
Raw Pointers: When Safe Rust Isn't Enough#
// FFI: Calling a C function that takes a pointer
extern "C" {
fn strlen(s: *const std::ffi::c_char) -> usize;
}
fn safe_strlen(s: &str) -> usize {
let c_str = std::ffi::CString::new(s).unwrap();
unsafe { strlen(c_str.as_ptr()) } // Raw pointer passed to C
}
fn main() {
println!("Length: {}", safe_strlen("hello"));
}
Raw pointers are necessary for FFI (calling C functions), implementing custom allocators, building certain data structures (doubly-linked lists, graphs), and interfacing with hardware registers in embedded systems. But they should always be wrapped in a safe API:
// PATTERN: Unsafe internals, safe API
struct SafeBuffer {
ptr: *mut u8,
len: usize,
}
impl SafeBuffer {
fn new(size: usize) -> Self {
let layout = std::alloc::Layout::array::<u8>(size).unwrap();
let ptr = unsafe { std::alloc::alloc(layout) };
SafeBuffer { ptr, len: size }
}
fn get(&self, index: usize) -> Option<u8> {
if index < self.len {
Some(unsafe { *self.ptr.add(index) }) // Bounds-checked before unsafe
} else {
None
}
}
}
impl Drop for SafeBuffer {
fn drop(&mut self) {
let layout = std::alloc::Layout::array::<u8>(self.len).unwrap();
unsafe { std::alloc::dealloc(self.ptr, layout); }
}
}
Option<&T>: Nullable References Done Right#
fn find_first_negative(data: &[i32]) -> Option<&i32> {
data.iter().find(|&&x| x < 0)
}
fn main() {
let numbers = vec![1, 2, -3, 4];
match find_first_negative(&numbers) {
Some(n) => println!("Found negative: {}", n),
None => println!("No negatives found"),
}
// No null check forgotten — the type FORCES you to handle both cases
}
Option<&T> is Rust's replacement for nullable pointers. The compiler won't let you use the reference without first checking whether it exists. Tony Hoare called null references his "billion-dollar mistake"—Rust's Option is the correction.
Broader Implications: Pointers Without the Pain#
At RantAI, references are how our systems share data across module boundaries without copying. Our inference pipeline passes &[f32] slices through preprocessing stages—each stage reads the same memory without allocating. Raw pointers appear only in our CUDA FFI layer, wrapped in safe abstractions that our application code never touches directly.
Practical Applications & Strategic Takeaways#
For newcomers: Use &T and &mut T for everything. You'll almost never need raw pointers in application code.
For C veterans: Rust references are like C pointers that can't be null, can't dangle, and can't alias mutably. The compiler enforces what you've been doing by convention.
For FFI developers: Wrap every raw pointer interaction in a safe API. The unsafe code should be a thin layer at the boundary, not scattered throughout your codebase.
Our Commitment to Open Knowledge#
RantAI is committed to open education. Pointers and references are covered in Chapter 10 of our guide, "The Rust Programming Language," freely available online.
Explore these concepts further: https://trpl.rantai.dev
Support Our Mission & Get Your Handbook#
Get the Handbook on Amazon KDP: https://www.amazon.com/dp/B0DHCMD3F2
Get the Handbook on Google Play Books: https://play.google.com/store/books/details?id=INwfEQAAQBAJ
How much of your Rust code uses raw pointers vs references? Share your ratio and use cases below!
#RustLang #Pointers #References #MemorySafety #RantAI #LearnRust #FFI #RawPointers #SystemsProgramming #NullSafety
Artikel berikutnya
References in Practice: Data Race Prevention, Interior Mutability, and the C++ Comparison