Skip to main content

Slices: borrowing part of a collection

A slice is a reference plus a length. It borrows a contiguous run of elements from an array, a `Vec` or a `String`, and copies nothing at all.

Writing functions that take `&[T]` instead of `&Vec<T>` (and `&str` instead of `&String`) makes them usable with more callers for free — arrays, vectors and sub-ranges all coerce to a slice.

Because a slice borrows, the borrow checker keeps the underlying collection from being resized while the slice is alive. That is the rule that makes iterator invalidation impossible.

Mutating while a slice is alive

fn main() {
    let mut items = vec![1, 2, 3];
    let window = &items[0..2];
    items.push(4);            // error[E0502]
    println!("{window:?}");
}

error[E0502]: cannot borrow `items` as mutable because it is also borrowed as immutable

Finish with the slice before mutating, or copy the values you need out of it first. A `push` can reallocate the buffer, which would leave the slice pointing at freed memory — so Rust refuses.

Run it and change it

The editor below is live: edit anything and the real compiler output updates by itself.

Your Rust