Ownership and Borrowing

Rust Slices: &str and &[T]

Borrow part of a string or array without copying a single byte.

  • Intermediate
  • 2 min read
  • 1 runnable example
What you'll learn
  • String slices
  • Array slices
  • Returning a slice
&numbers[1..4]
100
201
302
403
504
The slice covers indexes 1, 2 and 3.

A view of part of a collection

A slice is a reference to a continuous part of a collection. &text[0..5] borrows the first five bytes of a string, and &numbers[1..4] borrows three items of an array.

first_word returns a slice of the text it was given, so nothing is copied. find returns the position of the first space, or None when there is none. A slice of an array works the same way and has methods such as iter and len.

Key points

  1. &text[0..5] borrows the first five bytes.
  2. A slice does not copy the data.
  3. &numbers[1..4] has three items.

Runnable Rust example

Rust
Run code →
main.rs
fn first_word(text: &str) -> &str {
    match text.find(' ') {
        Some(index) => &text[..index],
        None => text,
    }
}

fn main() {
    let sentence = String::from("ownership makes Rust safe");
    println!("{}", first_word(&sentence));
    println!("{}", &sentence[10..15]);

    let numbers = [10, 20, 30, 40, 50];
    let middle = &numbers[1..4];
    println!("{:?} sum = {}", middle, middle.iter().sum::<i32>());
}
Get a Run button for this example Result of running the code
ownership
makes
[20, 30, 40] sum = 90

Practice

Open the example in the online compiler, change a value or add a line, and predict the output before you run it. Then break the code on purpose and read the compiler's message.

Finished this lesson?

Mark it as learned to track your progress.

Next: Lifetimes →

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges