Skip to main content
Be Bitwise
RustBorrowing & Lifetimes

Slices

Slices let you point at a contiguous chunk of a collection without taking ownership. You'll reach for them constantly in Rust.

String Slices

A string slice (&str) is a reference to part of a String:

rust
let s = String::from("hello world");
let hello = &s[0..5]; // "hello"
let world = &s[6..11]; // "world"

Shorthand:

rust
let hello = &s[..5]; // from start
let world = &s[6..]; // to end
let full = &s[..]; // entire string

Those ranges count bytes, not characters. That's fine for ASCII, but a range that ends inside a multi-byte UTF-8 character panics at runtime, so a parser that slices untrusted input this way can be crashed on demand.

Try itUncomment the marked line to see the panic, then compare it with the chars()-based version underneath.
Rust (1.40.0)

&str vs String

TypeOwned?Mutable?Where?
StringYesYes (if mut)Heap
&strNo (borrowed)NoAnywhere
rust
let owned: String = String::from("hello"); // owns heap data
let slice: &str = &owned; // borrows it
let literal: &str = "hello"; // string literal (in binary)

In memory, the difference is one field. A String is three words on the stack (pointer, length, capacity) and owns its heap buffer. A &str is two words, pointer and length, and owns nothing. Because it carries its length alongside the pointer it's called a fat pointer. Here are s, hello and world from the top of the lesson:

A &[T] has exactly the same shape, except its length counts elements rather than bytes. Neither slice could outlive s, since freeing that heap buffer would leave both pointers dangling. That's the rule the borrow checker enforces.

Key Concept

Take &str in function parameters, not &String. A &str swallows both String references and string literals, so your function takes more callers without breaking a sweat. Same reasoning as taking &[T] instead of &Vec<T>.

Array Slices

The same concept applies to arrays and vectors:

rust
let numbers = [1, 2, 3, 4, 5];
let middle: &[i32] = &numbers[1..4]; // [2, 3, 4]
let v = vec![10, 20, 30, 40];
let first_two: &[i32] = &v[..2]; // [10, 20]

Slices Prevent Bugs

Consider this C-like bug:

rust
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &byte) in bytes.iter().enumerate() {
if byte == b' ' {
return &s[..i];
}
}
&s[..]
}
let mut s = String::from("hello world");
let word = first_word(&s);
// s.clear(); // ERROR: cannot borrow s as mutable while word borrows it
println!("{}", word);

Pull this stunt in C and you've earned yourself a use-after-free. In Rust, the borrow checker shoots it down before the program ever runs.

Try it. The borrow ends at word's last use, so the second clear() further down is fine.

Try itUncomment the early s.clear() and read the error, then notice that the later call compiles because word is no longer in use.
Rust (1.40.0)

Iterating with Slices

rust
fn sum(numbers: &[i32]) -> i32 {
let mut total = 0;
for &n in numbers {
total += n;
}
total
}
let arr = [1, 2, 3, 4, 5];
let v = vec![10, 20, 30];
println!("{}", sum(&arr)); // 15
println!("{}", sum(&v)); // 60
println!("{}", sum(&v[..2])); // 30

One signature, three call sites. The slice doesn't care whether it came from an array, a vector, or a slice of a slice.