Langsung ke konten
Semua insights

Academy

The Reference Spectrum: From Fat Pointers to Raw Pointers in Rust

Explore the spectrum of pointers in Rust, from safe references and fat-pointer slices to raw pointers in `unsafe` blocks for FFI and low-level memory control.

6 menit baca

The Reference Spectrum: From Fat Pointers to Raw Pointers in Rust
Di halaman ini

If you learned systems programming through C, pointers were your first love and your longest nightmare. They're the most powerful tool in C's arsenal and simultaneously the source of its most devastating bugs. A pointer can address any byte in memory, perform arithmetic to navigate data structures, and cast between types with reckless abandon. It can also dereference null, read freed memory, write past buffer boundaries, and corrupt the stack in ways that produce security vulnerabilities exploitable from across the internet.

Rust looked at the pointer and asked: what if we separated the capability (referring to data elsewhere in memory) from the danger (unrestricted access to arbitrary memory)? The result is Rust's reference system—&T and &mut T—which provides all the referencing capability that 99% of code needs, with compile-time guarantees that the reference is non-null, properly aligned, pointing to valid data of the correct type, and not outliving the data it points to.

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 offer C-like power within explicitly marked unsafe blocks. You get full control when you need it, but the dangerous code is isolated, visible, and auditable.

At RantAI, this layered approach to pointers is what lets us maintain large codebases with confidence. Our application code uses references exclusively—safe, verified, impossible to misuse. Our FFI bindings to C libraries use raw pointers—dangerous but contained within thin unsafe wrappers that expose safe interfaces. 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 with Guarantees#

Rust
fn main() {
    let data = vec![10, 20, 30, 40, 50];
    
    // &T: immutable reference — safe pointer to read-only data
    let first: &i32 = &data[0];
    println!("First element: {}", first);  // Dereferencing is automatic
    
    // References are guaranteed:
    // ✓ Non-null (no Option needed unless absence is possible)
    // ✓ Aligned (hardware requirements satisfied)
    // ✓ Valid (points to initialized data of type T)
    // ✓ Non-dangling (lifetime system proves it)
}

References in Rust are fat pointers for slices and trait objects (pointer + metadata) or thin pointers for sized types (just an address). Either way, the compiler guarantees their validity at every use site.

The Reference Hierarchy#

Rust
fn main() {
    let mut value = 42;
    
    // Shared reference: multiple readers allowed
    let r1 = &value;
    let r2 = &value;
    println!("{} {}", r1, r2);  // Both valid simultaneously
    
    // Exclusive reference: one writer, no readers
    let r3 = &mut value;
    *r3 = 100;
    println!("{}", r3);  // Only r3 can access value right now
    
    // After r3 is done, value is accessible again
    println!("{}", value);  // 100
}

Shared references (&T) are like read-only pointers that can be freely copied. Exclusive references (&mut T) are like write pointers with a "no trespassing" sign—while one exists, nothing else can access the data. This duality prevents data races at compile time.

Slices: Fat Pointers to Contiguous Memory#

Rust
fn sum(data: &[i32]) -> i32 {
    data.iter().sum()
}

fn main() {
    let array = [1, 2, 3, 4, 5];
    let vector = vec![10, 20, 30];
    
    // Slices work with both arrays and vectors
    println!("Array sum: {}", sum(&array));      // &[i32; 5] coerces to &[i32]
    println!("Vector sum: {}", sum(&vector));     // &Vec<i32> coerces to &[i32]
    println!("Partial sum: {}", sum(&array[1..4])); // Slice of elements 1,2,3
    
    // A slice is a fat pointer: (pointer to first element, length)
    // It carries bounds information, enabling runtime bounds checking
}

Slices (&[T]) are Rust's answer to "pointer + length"—the pattern that C gets wrong more than any other. A slice knows its length, so every index access is bounds-checked. Buffer overflows—the #1 source of security vulnerabilities in C code—are impossible with slices.

Raw Pointers: When You Need C-Level Control#

Rust
fn main() {
    let x = 42;
    
    // Creating raw pointers is safe
    let raw_const: *const i32 = &x as *const i32;
    let raw_mut: *mut i32 = &x as *const i32 as *mut i32;
    
    // DEREFERENCING raw pointers requires unsafe
    unsafe {
        println!("Raw value: {}", *raw_const);
    }
    
    // Raw pointers can be:
    // - Null (*const i32 can be std::ptr::null())
    // - Dangling (no lifetime checking)
    // - Unaligned (no alignment guarantee)
    // - Cast between types (no type checking)
    // That's why dereferencing is unsafe!
}

When Raw Pointers Are Necessary#

Rust
// FFI: calling C functions that expect raw pointers
extern "C" {
    fn strlen(s: *const std::ffi::c_char) -> usize;
}

fn safe_strlen(s: &std::ffi::CStr) -> usize {
    unsafe { strlen(s.as_ptr()) }  // Raw pointer used only inside unsafe
}

// Custom allocators, intrusive data structures, memory-mapped I/O
// These rare cases need raw pointers, but they're always wrapped
// in safe abstractions that users interact with through references

The pattern is consistent: raw pointers live inside unsafe blocks, wrapped by safe functions that expose reference-based APIs. Users of the safe API never touch raw pointers. The unsafe code is concentrated, auditable, and testable.

The Safety Spectrum#

Pointer Type Safety Guarantees Use Case &T Safe Non-null, valid, aligned, non-dangling 99% of code &mut T Safe All of &T + exclusive access Mutation &[T] Safe All of &T + bounds-checked length Arrays/slices *const T Unsafe to deref None FFI, low-level *mut T Unsafe to deref None FFI, low-level

Broader Implications: Pointers Without the Pain#

At RantAI, references are our default. Raw pointers appear only in our FFI layer (calling into C ML libraries) and in two custom data structures. That's it. Every other pointer operation in our codebase uses references—verified safe by the compiler, impossible to misuse, zero runtime overhead compared to raw pointers.

Practical Applications & Strategic Takeaways#

For newcomers: Use &T and &mut T for everything. You'll rarely need raw pointers unless you're doing FFI or implementing unsafe data structures.

For C veterans: Rust's references are what C pointers would be if the compiler verified every access. Same performance, dramatically fewer bugs.

For library authors: Wrap unsafe pointer operations in safe APIs. Your users should never see *const T or *mut T—they should interact with &T and &mut T through your safe interface.

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#

How has switching from raw pointers to references changed how you think about memory? Share your pointer evolution story below!

#RustLang #Pointers #References #MemorySafety #RantAI #LearnRust #Slices #FFI #UnsafeRust #SystemsProgramming

Artikel berikutnya

Slide 1 · Sampul. Judul serif dua baris. Standfirst sans 34 px biru tua. Kaki: tanggal kiri, sumber kanan. A Commit Is N