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:
let s = String::from("hello world");let hello = &s[0..5]; // "hello"let world = &s[6..11]; // "world"Shorthand:
let hello = &s[..5]; // from startlet world = &s[6..]; // to endlet full = &s[..]; // entire stringThose 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.
&str vs String
| Type | Owned? | Mutable? | Where? |
|---|---|---|---|
String | Yes | Yes (if mut) | Heap |
&str | No (borrowed) | No | Anywhere |
let owned: String = String::from("hello"); // owns heap datalet slice: &str = &owned; // borrows itlet 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.
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:
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:
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 itprintln!("{}", 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.
Iterating with Slices
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)); // 15println!("{}", sum(&v)); // 60println!("{}", sum(&v[..2])); // 30One signature, three call sites. The slice doesn't care whether it came from an array, a vector, or a slice of a slice.