Rust
Beginner
1 min read
Lifetime Annotations
Example
// Lifetime annotation: the returned reference lives as long as
// the shorter-lived of x and y.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() >= y.len() { x } else { y }
}
// Struct holding a reference must declare a lifetime parameter
struct Excerpt<'a> {
part: &'a str,
}
impl<'a> Excerpt<'a> {
// Elided: &self has lifetime 'a, return shares 'a
fn content(&self) -> &str {
self.part
}
}
fn main() {
let s1 = String::from("long string is long");
let result;
{
let s2 = String::from("xyz");
result = longest(s1.as_str(), s2.as_str());
println!("longest = {result}");
}
// result cannot be used here — s2 dropped above
// Struct with a reference
let novel = String::from("Call me Ishmael. Some years ago...");
let first_sentence = novel.split('.').next().unwrap();
let ex = Excerpt { part: first_sentence };
println!("excerpt: {}", ex.content());
// 'static lifetime — valid for entire program
let s: &'static str = "I am embedded in the binary";
println!("{s}");
}