Sub topic 3
`'static`: String Literals and `T: 'static`
Assume ownership, borrowing, generics, structs, and String versus &str. A lifetime bound describes how long a reference may remain valid. It does not automatically extend the lifetime of data.
`'static` and Generic Bounds
A &'static str points to data that remains valid for the whole program. String literals have this lifetime because they are stored in the program's binary.
T: 'static means that a value of type T contains no references shorter than 'static. Owned values usually satisfy this bound. A reference to a local variable does not.
use std::fmt::Debug;
fn print_it<T: Debug + 'static>(value: T) {
println!("{value:?}");
}
fn main() {
print_it(String::from("owned"));
let text = String::from("local");
// print_it(&text); // error: `text` does not live long enough
}A generic lifetime bound can be less restrictive:
fn show<T: std::fmt::Display + 'a, 'a>(value: T) {
println!("{value}");
}In practice, write the lifetime before its use: fn show<'a, T: Display + 'a>(...).
Trait Objects and Closures
A boxed closure that borrows text must record that borrowing lifetime:
fn make_length<'a>(text: &'a str) -> Box<dyn Fn() -> usize + 'a> {
Box::new(move || text.len())
}Without + 'a, the trait object may be assumed to require 'static, rejecting the borrowed capture.
Errors, Higher-Ranked Bounds, and Variance
E0597 usually means a reference is used after its source is dropped. Fix it by shortening the use, moving ownership, or returning owned data. E0106 means a stored reference lacks a declared lifetime, such as struct Item { value: &str }; use struct Item<'a> { value: &'a str }.
A higher-ranked trait bound means “for every lifetime”:
fn apply<F>(f: F) -> usize
where
F: for<'a> Fn(&'a str) -> &'a str,
{
f(" hello ").len()
}The closure must work with any input lifetime chosen by apply.
Lifetime variance is an advanced subtyping rule. Shared references are covariant, so a reference valid longer can be used where a shorter one is expected. Mutable references are invariant in their referenced type, which prevents writes from introducing an invalid lifetime.
Exercise
Why does Box<dyn Fn() -> usize + 'a> need +'a when the closure captures &'a str?
Show answer
It prevents the boxed closure from outliving the borrowed string.