Langsung ke konten
Semua insights

Academy

Passing Arrays and Slices to Functions: Ownership, Borrowing, and Efficiency

Eliminate unnecessary data copies in Rust. Learn how to pass arrays and slices using ownership, immutable borrowing (&[T]), and mutable borrowing (&mut [T]).

5 menit baca

Passing Arrays and Slices to Functions: Ownership, Borrowing, and Efficiency
Di halaman ini

There's a performance antipattern so common it has become invisible: copying data into every function that needs to read it. Your web handler receives a request body. It copies the body into the parser. The parser copies tokens into the validator. The validator copies fields into the database query builder. The original 2KB request has been copied four times, consuming 8KB of memory and four allocation cycles, because nobody stopped to ask: "Does this function actually need its own copy, or can it just look at the original?"

Rust's ownership system forces you to answer this question explicitly for every function parameter. You can't accidentally copy a Vec<u8>—it moves instead, transferring ownership. You can't accidentally share a &mut [u8]—the compiler ensures exclusivity. Every function signature declares exactly what it does with the data: owns it, reads it, or modifies it. The result is code where data flows through processing stages with minimal copying, maximum clarity, and compiler-verified safety.

At RantAI, our data processing pipelines pass slices through dozens of functions without a single unnecessary copy. The compiler verifies that every borrow is valid, every mutation is exclusive, and every owned value is properly cleaned up. This article, drawn from Chapter 10 of our guide "The Rust Programming Language," covers the patterns for passing arrays and slices to functions efficiently.

The Three Modes: Own, Borrow, Borrow-Mut#

Rust
// MODE 1: Take ownership — the function consumes the data
fn archive(data: Vec<u8>) {
    // data is owned by this function, will be freed when function returns
    write_to_storage(data);
}

// MODE 2: Immutable borrow — the function reads the data
fn checksum(data: &[u8]) -> u32 {
    data.iter().fold(0u32, |acc, &byte| acc.wrapping_add(byte as u32))
}

// MODE 3: Mutable borrow — the function modifies the data
fn encrypt_in_place(data: &mut [u8], key: u8) {
    for byte in data.iter_mut() {
        *byte ^= key;
    }
}

fn main() {
    let mut buffer = vec![72, 101, 108, 108, 111];  // "Hello" as bytes
    
    // Read without consuming
    let sum = checksum(&buffer);
    println!("Checksum: {}", sum);
    
    // Modify in place
    encrypt_in_place(&mut buffer, 42);
    println!("Encrypted: {:?}", buffer);
    
    // Consume — buffer is gone after this
    archive(buffer);
    // println!("{:?}", buffer);  // COMPILE ERROR: buffer was moved
}

The Decision Framework#

Use &[T] (immutable slice) as your default for function parameters. This is the most flexible: it accepts Vec<T>, [T; N], and other slices. The caller keeps ownership. Multiple functions can read simultaneously.

Use &mut [T] (mutable slice) when the function needs to modify the data in place. The caller keeps ownership but grants exclusive write access.

Use Vec<T> (owned vector) when the function needs to store the data permanently, transfer it to another owner, or consume it as part of a larger operation.

Rust
// GOOD: accepts any contiguous i32 data
fn mean(data: &[i32]) -> f64 {
    data.iter().sum::<i32>() as f64 / data.len() as f64
}

// LESS FLEXIBLE: only accepts Vec<i32>
fn mean_vec_only(data: &Vec<i32>) -> f64 {
    data.iter().sum::<i32>() as f64 / data.len() as f64
}

fn main() {
    let vec = vec![1, 2, 3, 4, 5];
    let array = [10, 20, 30];
    
    mean(&vec);    // Works
    mean(&array);  // Works — slices accept arrays too!
    
    mean_vec_only(&vec);    // Works
    // mean_vec_only(&array);  // COMPILE ERROR: expected &Vec<i32>
}

Returning Arrays and Vectors#

Rust
// Return a new owned Vec (common pattern)
fn doubled(data: &[i32]) -> Vec<i32> {
    data.iter().map(|&x| x * 2).collect()
}

// Return a slice of the input (zero-copy, requires lifetime)
fn first_half(data: &[i32]) -> &[i32] {
    &data[..data.len() / 2]
}

fn main() {
    let nums = vec![1, 2, 3, 4, 5, 6];
    
    let d = doubled(&nums);     // New allocation, owned by caller
    let h = first_half(&nums);  // No allocation, borrows from nums
    
    println!("Doubled: {:?}", d);    // [2, 4, 6, 8, 10, 12]
    println!("First half: {:?}", h); // [1, 2, 3]
}

Returning &[T] avoids allocation but ties the result's lifetime to the input. Returning Vec<T> allocates but gives the caller independent ownership. Choose based on whether the caller needs the data to outlive the input.

Processing Pipelines: Zero-Copy Data Flow#

Rust
fn parse_records(raw: &[u8]) -> Vec<&[u8]> {
    raw.split(|&b| b == b'\n').collect()
}

fn filter_valid(records: &[&[u8]]) -> Vec<&[u8]> {
    records.iter()
        .filter(|r| !r.is_empty() && r[0] != b'#')  // Skip empty and comments
        .copied()
        .collect()
}

fn count_fields(record: &[u8]) -> usize {
    record.split(|&b| b == b',').count()
}

fn main() {
    let raw_data = b"name,age,city\n# comment\nAlice,30,NYC\nBob,25,LA\n";
    
    let records = parse_records(raw_data);
    let valid = filter_valid(&records);
    
    for record in &valid {
        println!("{} fields: {}", 
            String::from_utf8_lossy(record),
            count_fields(record));
    }
    // Zero copies of the actual data — everything borrows from raw_data
}

This pipeline processes the raw byte data without copying it. Each stage borrows from the original buffer. The compiler verifies that raw_data outlives all the slices derived from it.

Broader Implications: Efficiency by Design#

At RantAI, the slice-based parameter pattern means our processing functions are both generic (accept any contiguous data source) and efficient (no unnecessary copying). A function that takes &[Record] works with vectors, arrays, and subranges—without knowing or caring which one the caller provided.

Practical Applications & Strategic Takeaways#

For newcomers: Always prefer &[T] over &Vec<T> in function parameters. It's more flexible and more idiomatic.

For pipeline architects: Design processing stages as functions that take &[T] and return either &[T] (zero-copy derived view) or Vec<T> (new computed data). This naturally creates efficient, composable pipelines.

For performance engineers: Profile allocation patterns. Every Vec<T> return is a heap allocation. If the caller only needs a temporary view, return a slice instead.

Our Commitment to Open Knowledge#

RantAI is committed to open education. Passing arrays and slices to functions is 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 do you decide between &[T] and Vec<T> in your function signatures? Share your patterns below!

#RustLang #Slices #Functions #ZeroCopy #RantAI #LearnRust #Performance #Ownership #Borrowing #SystemsProgramming

Artikel berikutnya

Lifetime Patterns in Practice: From Dangling References to Zero-Copy Pipelines