Course contentsShow
← Rust
Lesson 204 of 1,9103. Borrowing and ReferencesFree lesson

Borrowing Slices from Collections

Use slice references to create views into contiguous memory buffers.

In this lesson, you will learn how to create "slices," which are views that allow you to look at a specific, contiguous portion of a collection without taking ownership of the entire data structure.

Looking Through a Window

When you have a large collection, such as a Vec<i32> or a String, you might only want to work with a small part of it. If you passed the whole collection around, you would be passing a lot of data unnecessarily. Instead, Rust allows you to "borrow" a slice. Think of a slice as a window into a portion of a collection's memory. Because a slice is a reference, it doesn't own the data; it simply points to a start index and a length, allowing you to read or interact with that specific range.

Creating a Slice

You create a slice by using the range syntax [start..end] inside square brackets. The range is inclusive of the start index and exclusive of the end index.

fn main() {
    let numbers = vec![10, 20, 30, 40, 50];

    // We borrow a slice from index 1 up to (but not including) 4
    let slice = &numbers[1..4];

    println!("The slice contains: {:?}", slice);
}

In this example, slice is a &[i32]. It doesn't own the numbers vector; it is just a borrowed view. Because it is a reference, the borrow checker ensures that your slice remains valid as long as the original numbers vector exists. If you tried to modify or destroy the numbers vector while the slice was still in use, the compiler would stop you, preventing any memory safety issues like accessing invalid indices.

Why use slices?

Slices are incredibly efficient because they don't copy the data. They simply record the memory address of the first element and the count of how many items to include. Whether your collection has ten elements or ten million, creating a slice is always a fast, constant-time operation. By using slices, you make your functions more flexible, allowing them to accept either a whole collection or just a specific section of one.

Key Takeaway: A slice is an immutable reference that acts as a lightweight, non-owning window into a contiguous portion of a collection.