Sub topic 2
String Slices and UTF-8 Boundaries
Prerequisites: ownership, borrowing, references, and basic String and Vec<T> use. A slice is a borrowed view into existing data. This chapter focuses on &str, function parameters, and borrowing rules.
String slices and UTF-8 boundaries
A string slice, written &str, refers to part of a UTF-8 string without owning or copying it. Rust string indices are byte offsets, not character positions. A character such as é uses two bytes, so a slice must begin and end on valid UTF-8 character boundaries.
fn main() {
let text = "héllo";
println!("{}", &text[0..1]);
println!("{:?}", text.get(0..2)); // None: byte 2 is inside é
}Direct indexing with an invalid range panics. The get method returns None instead, which lets your program handle invalid ranges safely. Use char_indices when you need character-aware positions rather than byte offsets.
Accepting slices in function parameters
Functions should usually accept &str when they only need to read text. This accepts both string literals and borrowed String values through deref coercion, which automatically converts &String to &str.
fn first_word(text: &str) -> &str {
match text.find(' ') {
Some(index) => &text[..index],
None => text,
}
}
fn main() {
let message = String::from("hello world");
println!("{}", first_word(&message));
println!("{}", first_word("single"));
}The returned slice cannot outlive the input borrow. It points into the same string, so Rust tracks that relationship automatically.
How the borrow checker treats slices
A slice is a reference, so its lifetime and access permissions follow normal borrowing rules. While an immutable slice exists, the borrowed data cannot be changed. A mutable slice, &mut [T], provides exclusive access.
fn main() {
let mut values = [1, 2, 3, 4];
let (left, right) = values.split_at_mut(2);
left[0] = 10;
right[0] = 20;
println!("{values:?}");
}split_at_mut proves that the two mutable slices do not overlap. Without that proof, two mutable references to the same data could cause conflicting writes.
Exercise
Why does text.get(0..2) return None for "héllo"?
Show answer
The second byte lies inside the two-byte UTF-8 encoding of é, so the range does not end on a character boundary.