← Back to Rust Course | Chapter 6: Borrowing & References | Lesson 5 of 6

Slices

A slice is like a window that shows you just part of a bigger list, without needing to copy any of it out.

Slicing an Array

A slice references a contiguous portion of a collection using range syntax inside square brackets, without copying the underlying elements.

Example: Slicing an Array

markup
fn main() {
    let numbers = [10, 20, 30, 40, 50];
    let middle = &numbers[1..4];
    println!("{:?}", middle);
}

Slicing a Vector

Slices work the same way on a Vec, letting you view a portion of it as &[T] while the Vec itself keeps ownership of the data.

Example: Slicing a Vector

markup
fn main() {
    let scores = vec![90, 85, 77, 92];
    let top_two = &scores[0..2];
    println!("Top two: {:?}", top_two);
}

Full Slices

Omitting both ends of a range, &collection[..], produces a slice covering the entire collection, which is useful when a function parameter expects a slice type rather than an owned collection.

Example: Full Slices

markup
fn total(values: &[i32]) -> i32 {
    values.iter().sum()
}

fn main() {
    let data = vec![1, 2, 3, 4];
    println!("Sum: {}", total(&data[..]));
}

Slices Borrow Their Source

Because a slice is a reference, it follows the same borrowing rules: the original collection cannot be mutated while an active slice of it still exists.

Example: Slices Borrow Their Source

markup
fn main() {
    let letters = ['a', 'b', 'c', 'd'];
    let part = &letters[1..3];
    println!("Slice: {:?}", part);
    println!("Original still usable: {:?}", letters);
}
Common Mistakes
  1. Trying to slice out of bounds, e.g. &array[0..10] on a 5-element array, which panics at runtime.
  2. Forgetting slices borrow from the original data, so the original collection cannot be mutated while a slice of it is in use.
  3. Confusing &vec[..] (a slice of the whole vector) with vec itself (an owned value) when passing data to functions.
Chapter Summary
  • A slice, written &[T] or &str, references a contiguous sequence of elements without owning them.
  • Range syntax like 1..3 selects a sub-range of a collection to slice.
  • Slices borrow from their source, so borrowing rules still apply to them.
  • Slices let functions accept both full collections and partial views with one flexible parameter type.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.