Rust

Slice Pattern: Borrow Without Copy

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
A slice (`&[T]`) is a borrowed view into a contiguous sequence. Pass `&v[..]` or just `&v` instead of `v.clone()` when the function only needs to read.
Rust
Raw
fn sum(values: &[i32]) -> i32 {       // accepts any slice
    values.iter().sum()
}

fn first_word(s: &str) -> &str {       // returns a borrowed slice
    match s.find(' ') {
        Some(i) => &s[..i],
        None    => s,
    }
}

fn main() {
    let v = vec![1, 2, 3, 4, 5];
    println!("{}", sum(&v));            // pass whole Vec as slice
    println!("{}", sum(&v[1..4]));      // pass sub-slice — no copy

    let s = String::from("hello world");
    println!("first: {}", first_word(&s));    // "hello"
    // s is still owned and usable
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.