Sub topic 2
Slices, Dangling References, and Lifetimes
Assume you know basic Rust syntax, String, Vec, &str, and how to run a Cargo program. A slice is a borrowed view into part of a collection. It does not own the data.
Slices: borrowing part of a collection
A string slice, written &str, refers to part of a string. An array or vector slice, written &[T], refers to consecutive elements.
fn first_word(text: &str) -> &str {
text.split_whitespace().next().unwrap_or("")
}
fn main() {
let sentence = String::from("borrowing is useful");
let word = first_word(&sentence);
println!("{word}");
}The function borrows sentence and returns a slice into it. The returned slice cannot outlive sentence.
A slice is useful when a function needs to inspect data without copying it or taking ownership.
Dangling references and how Rust rejects them
A dangling reference points to data that has already been dropped. Rust rejects such code at compile time.
fn dangle() -> &String {
let text = String::from("temporary");
&text
}
fn main() {
let _reference = dangle();
}This fails because text is local to dangle and is dropped when the function returns. Returning &text would create a dangling reference. Return an owned String instead:
fn make_text() -> String {
String::from("temporary")
}Where a borrow ends: non-lexical lifetimes
A borrow lasts until its final use, not always until the end of its surrounding block. This behavior is called non-lexical lifetimes.
fn main() {
let mut text = String::from("a");
let view = &text;
println!("{view}");
let edit = &mut text;
edit.push('b');
println!("{edit}");
}The shared borrow ends after println!("{view}"), so the mutable borrow is allowed afterward. If view were used after edit was created, Rust would reject the program.
Lifetime annotations on functions
A lifetime annotation describes how references in a function relate to one another. It does not extend a reference's life.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() >= y.len() { x } else { y }
}
fn main() {
let left = String::from("apple");
let right = String::from("fig");
println!("{}", longest(&left, &right));
}The annotation says the result is valid for the shorter lifetime of x and y. The function may return either input, so Rust needs this relationship stated explicitly.
Exercise
Why can longest return a reference but dangle cannot?
Show answer
longest returns data borrowed from its inputs, which remain owned by the caller. dangle returns data borrowed from a local variable that is dropped before the caller can use it.