// The compiler needs to know: the returned reference lives as long as
// the SHORTER of the two inputs. The 'a lifetime expresses that.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() >= y.len() { x } else { y }
}
fn main() {
let s1 = String::from("long string is long");
let result;
{
let s2 = String::from("short");
result = longest(s1.as_str(), s2.as_str());
// result borrows from s2 — must be used while s2 is still alive
println!("longest: {result}");
}
// println!("{result}"); // ❌ s2 went out of scope
}
// Struct that holds a reference also needs a lifetime parameter:
struct Excerpt<'a> {
text: &'a str,
}
Create a free account and build your private vault. Share publicly whenever you want.