Langsung ke konten
Semua insights

Academy

Slices: The Safe Window into Contiguous Memory

Discover how Rust slices (&[T]) solve C's buffer overflow vulnerability by pairing a pointer with length metadata for safe, zero-copy data processing.

6 menit baca

Slices: The Safe Window into Contiguous Memory
Di halaman ini

C has a legendary footgun: arrays decay to pointers when passed to functions. A function that receives int* has no idea how many elements the pointer points to. Pass a 5-element array and the function might read 50 elements—buffer overflow, security vulnerability, CVE. The entire history of C buffer overflow exploits traces back to this single design decision: pointers don't carry length information.

Rust's answer is the slice: a reference to a contiguous sequence of elements that carries both a pointer and a length. A &[i32] is 16 bytes on 64-bit systems—8 bytes for the pointer, 8 bytes for the length. The function that receives it knows exactly how many elements are available. Bounds checking is automatic. Buffer overflows are impossible in safe code.

Slices are one of Rust's most practically important features. They're how you pass arrays and vectors to functions without copying. They're how you take subsets of data without allocating. They're how string processing works (&str is a string slice). And they're zero-cost—the bounds checks are optimized away when the compiler can prove they're unnecessary (which is most of the time in iterator-based code).

At RantAI, slices are the primary data access pattern in our numerical pipelines. Raw data comes in as Vec<f64>, and every processing function takes &[f64]—a view into the data without ownership or copying. This article, drawn from Chapter 10 of our guide "The Rust Programming Language," covers slices, string slices, and the fat-pointer design that makes them safe.

Array Slices: Views into Contiguous Data#

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

fn mean(data: &[f64]) -> f64 {
    data.iter().sum::<f64>() / data.len() as f64
}

fn main() {
    let array = [1, 2, 3, 4, 5];
    let vector = vec![1.0, 2.0, 3.0, 4.0, 5.0];
    
    // Both arrays and vectors can be sliced
    println!("Array sum: {}", sum(&array));      // &[i32; 5] coerces to &[i32]
    println!("Vector mean: {:.1}", mean(&vector)); // &Vec<f64> coerces to &[f64]
    
    // Sub-slices: views into portions of the data
    println!("First 3 sum: {}", sum(&array[..3]));  // Elements 0, 1, 2
    println!("Last 3 sum: {}", sum(&array[2..]));   // Elements 2, 3, 4
    println!("Middle sum: {}", sum(&array[1..4]));   // Elements 1, 2, 3
}

Slices work with both arrays ([T; N]) and vectors (Vec<T>). The function doesn't care which backing storage the data comes from—it just sees a pointer and a length. This is abstraction without overhead: one function works with any contiguous data source.

Mutable Slices#

Rust
fn double_all(data: &mut [i32]) {
    for value in data.iter_mut() {
        *value *= 2;
    }
}

fn main() {
    let mut numbers = vec![1, 2, 3, 4, 5];
    double_all(&mut numbers[1..4]);  // Double only elements 1, 2, 3
    println!("{:?}", numbers);  // [1, 4, 6, 8, 5]
}

Mutable slices (&mut [T]) give you exclusive write access to a portion of contiguous data. The borrowing rules still apply—you can't have a mutable slice and an immutable slice to overlapping regions simultaneously.

String Slices: Text Without Allocation#

Rust
fn first_word(s: &str) -> &str {
    match s.find(' ') {
        Some(i) => &s[..i],
        None => s,
    }
}

fn main() {
    let sentence = String::from("hello beautiful world");
    let word = first_word(&sentence);  // &str slice into the String
    println!("First word: {}", word);  // "hello"
    
    // String literals are also slices
    let literal: &str = "hello";  // Points to data in the binary
    println!("Literal: {}", literal);
}

&str is a slice into UTF-8 encoded text. It's 16 bytes (pointer + length) regardless of how long the text is. String functions that take &str work with both String (heap-allocated) and string literals (embedded in the binary)—same function, any text source.

Fat Pointers: The Design That Makes Slices Work#

Rust
use std::mem;

fn main() {
    // Regular reference: just a pointer (8 bytes on 64-bit)
    println!("Size of &i32: {}", mem::size_of::<&i32>());  // 8
    
    // Slice reference: pointer + length (16 bytes on 64-bit)
    println!("Size of &[i32]: {}", mem::size_of::<&[i32]>());  // 16
    
    // String slice: pointer + length (16 bytes on 64-bit)
    println!("Size of &str: {}", mem::size_of::<&str>());  // 16
    
    // The length is carried WITH the pointer
    let data = vec![10, 20, 30, 40, 50];
    let slice = &data[1..4];
    println!("Slice length: {}", slice.len());  // 3 — the slice KNOWS its size
}

Slices are "fat pointers"—they carry metadata (the length) alongside the data pointer. This extra 8 bytes is the price of safety: every bounds check can verify against the known length, and buffer overflows become impossible.

Splitting: Safe Concurrent Access to Different Parts#

Rust
fn main() {
    let mut data = vec![1, 2, 3, 4, 5, 6, 7, 8];
    
    // split_at_mut gives you two non-overlapping mutable slices
    let (left, right) = data.split_at_mut(4);
    
    // Both can be modified simultaneously — they don't overlap!
    for val in left.iter_mut() { *val *= 10; }
    for val in right.iter_mut() { *val *= 100; }
    
    println!("{:?}", data);  // [10, 20, 30, 40, 500, 600, 700, 800]
}

split_at_mut is the safe way to get two mutable references to different parts of the same data. The compiler can verify they don't overlap, so both can be modified independently—even from different threads.

Broader Implications: Zero-Copy Data Processing#

At RantAI, slices enable zero-copy data pipelines. Raw sensor data arrives as Vec<f64>. Analysis functions take &[f64] slices—they read the data without copying it. Transformation functions take &mut [f64]—they modify in place without allocating. The entire pipeline processes gigabytes of data through views and sub-views, with the only allocation being the initial vector.

Practical Applications & Strategic Takeaways#

For newcomers: Write functions that take &[T] instead of &Vec<T>. Slices are more general—they accept arrays, vectors, and sub-slices—while &Vec<T> only accepts vectors.

For C veterans: Slices are what you wished C arrays were: pointers that know their length. Buffer overflows are compile-time or runtime errors, not silent memory corruption.

For performance engineers: Iterator-based slice processing (slice.iter().map(...).sum()) often eliminates bounds checks entirely through compiler optimization. Prefer iterators over manual indexing.

Our Commitment to Open Knowledge#

RantAI is committed to open education. Slices and arrays 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#

Do you take &[T] or &Vec<T> in your function signatures? Share your reasoning!

#RustLang #Slices #Arrays #FatPointers #RantAI #LearnRust #ZeroCopy #BufferOverflow #MemorySafety #SystemsProgramming

Artikel berikutnya

Safe Wrappers and Null Safety: Building Safe APIs Over Raw Pointers with Option<&T>