Skip to content
Theory · Borrowing · lesson 9 of 11

Slices and &str

Sometimes a friend needs not the whole book but one chapter. You show them pages 10 to 25 without tearing anything out: the book stays whole and yours, and they read only their part.

Strings work the same way: you need only the first word or the end of the text. Copying the bytes into a new String for that is not appealing. For such cases Rust has slices.

A string slice

A slice is a reference to a contiguous part of a string or an array. A slice of a string is written like this: &s[0..4]. That is the & sign, the string's name and a range in square brackets — the same kind as in a for loop.

Rust
fn main() {
    let s = String::from("rust book");
    let a = &s[0..4];
    let b = &s[5..9];
    println!("{b} {a}"); // book rust
    println!("{} {}", &s[..4], &s[5..]); // rust book
    println!("{}", &s[..]); // rust book
}

The string rust book has nine characters numbered 0 to 8: r is number 0, the space is number 4, b is number 5. The numbers in a slice are byte numbers, but a Latin letter and a space take one byte each, so here the byte number matches the character number.

A slice copies nothing. It holds the address of the first byte and the length, and the bytes themselves stay in the string's unit.

Both bounds

&s[0..4] takes bytes 0 to 3, that is rust: the start is in the range, and the end is not. &s[5..9] takes bytes 5 to 8, the word book. The slice's length is the difference of the bounds: 4 − 0 = 4.

No start or no end

If the start is left out, the slice begins at byte zero: &s[..4] is the same as &s[0..4]. If the end is left out, the slice runs to the end of the string: &s[5..] is book, and you do not need to count the string's length.

The whole string

&s[..] is a slice from start to end, that is the whole string. It comes in handy when a function needs a slice and you have a whole String.

A slice is an ordinary & reference. So one string can have any number of slices at once, as in the first println!, and you cannot change the string while a slice of it is alive.

Here the borrow rule protects against reading freed memory. As you already know, push may move a string's text to a bigger unit and give the old unit back to the facility. A slice of the old unit's bytes would then point into freed memory. In C and C++ such code compiles, and the program may read garbage, but in Rust it does not pass the borrow checker.

The &str type

The type of a string slice is written &str. You have already met it: it is the type of a string literal. A literal's bytes are built into the program itself, and the literal is a slice that looks at them.

Rust
fn head(s: &str, n: usize) -> &str {
    &s[..n]
}

fn main() {
    let s = String::from("rust book");
    println!("{}", head(&s, 4)); // rust
    println!("{}", head("hello", 2)); // he
}

Let's go through the example line by line:

  1. head takes a string slice and a number n and returns the first n bytes.
  2. head(&s, 4) passes a reference to a String. Where a &str is expected, Rust turns the &String into a slice of the whole string on its own, and the function prints rust.
  3. head("hello", 2) passes a literal: it is already a &str, and the function returns he.

That is why a string parameter that is only read is usually declared as &str: such a function accepts both a &String and a literal. The result of head is a slice of the parameter, borrowed from the string passed into the function. Unlike a reference to a local variable, it will not dangle.

An array slice

You can slice an array too, with the same kind of range. The type of a slice of an i32 array is written &[i32]:

Rust
fn main() {
    let a = [10, 20, 30, 40, 50];
    let mid = &a[1..4];
    println!("{mid:?} {}", mid.len()); // [20, 30, 40] 3
}

&a[1..4] takes the elements numbered 1, 2 and 3. A slice is printed with {:?}, like the array itself, and len() returns the number of elements in the slice, 3.

Here the book-chapter analogy falls short. A chapter starts at the top of a page, but a string slice can start at any byte, even in the middle of a word. The compiler checks that a slice does not outlive its string, but it does not check the slice's bounds.

Common mistake

The slice's end is taken inclusively and runs into the string's length:

Rust
fn main() {
    let s = String::from("rust book");
    println!("{}", &s[5..=s.len()]); // ✗
}
TEXT
end byte index 9 is out of bounds for string of length 9

The program builds but panics when run. The string's length is 9, and the last byte is number 8. The range 5..=9 includes number 9, and the string has no such byte. It is the same mistake as 0..=a.len() in a loop over an array. The right form is &s[5..s.len()] or, shorter, &s[5..].

Key points

  • A slice is a reference to a contiguous part of a string or an array; it copies nothing.
  • &s[a..b] takes bytes a to b - 1; &s[..b] starts at the beginning, &s[a..] runs to the end, &s[..] is the whole string.
  • &str is the type of a string slice and of a literal; a &str parameter accepts both a &String and a literal.
  • Slice bounds are checked at run time: going past the end of the string is a panic.