Annotating Lifetimes in Functions and Structs
Annotating Lifetimes in Functions and Structs
When a function returns a reference that could come from multiple inputs, explicit lifetime annotations are required:
// The returned reference is guaranteed valid for the intersection of 'a
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
struct Excerpt<'a> {
part: &'a str,
}
fn main() {
let string1 = String::from("desk configuration");
let result;
{
let string2 = String::from("orders");
result = longest(string1.as_str(), string2.as_str());
println!("Longest string: {}", result);
}
}