Rust
Lifetimes
Explicit lifetime annotations.
By EZ4Code Team
lifetimelifetime
Code
// Lifetime annotation
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
// Lifetime in struct
struct Excerpt<'a> {
part: &'a str,
}
impl<'a> Excerpt<'a> {
fn announce(&self, msg: &str) -> &str {
println!("{}: {}", msg, self.part);
self.part
}
}
// Static lifetime
fn static_example() {
let s: &'static str = "I live forever";
println!("{}", s);
}
fn main() {
let s1 = String::from("long string");
let s2 = String::from("short");
let result = longest(s1.as_str(), s2.as_str());
println!("Longest: {}", result);
let novel = String::from("Call me Ishmael...");
let first = Excerpt { part: &novel[0..4] };
first.announce("Excerpt");
}Explanation
Lifetimes ensure references remain valid; 'a is a lifetime parameter; 'static means the entire program duration.