A lifetime annotation is Rust syntax that supplies extra information about how long references are expected to remain valid. It describes relationships between references and the values they borrow; it does not extend a value’s lifetime. Rust usually infers this information, but signatures sometimes need help. section 10.2 section 10.4
Use lifetime annotations to make reference relationships explicit:
- In functions, annotate returned references when Rust cannot determine what value they borrow from. A function cannot return a reference to a local value that is dropped before the function ends. section 10.2.1
- In types, write a lifetime parameter such as <'a> and connect a reference field such as name: &'a str to the containing value’s lifetime. section 10.2.2
- Treat 'static as a requirement for data that lives for the entire program, commonly string literals; it is a constraint, not a way to promote ordinary data. section 10.2.1 section 10.2.2
- Prefer owned data when avoiding lifetime annotations is more practical; use &'static str only when the type truly accepts program-long data. section 10.4
A borrowed field in City
Writing struct City<'a> { name: &'a str, date_founded: u32 } says that City carries a lifetime named 'a, and its name reference must remain valid for at least that lifetime. This permits a City to borrow from a string stored elsewhere, unlike &'static str, which accepts only data living for the whole program. section 10.2.2
#[derive(Debug)]
struct City<'a> { #1
name: &'a str, #2
date_founded: u32,
}
fn main() {
let city_names = vec!["Ichinomiya".to_string(), "Kurume".to_string()];
let my_city = City {
name: &city_names[0],
date_founded: 1921,
};
println!("{} was founded in {}", my_city.name, my_city.date_founded);
}
Inspect a complete City example using a lifetime parameter and a reference into a vector of owned strings. section 10.2.2

