Lifetimes and References
Longest Reference
Returning a Borrow
Lifetime annotations connect the returned reference to the input references it may point at.
Program
Play the program to compare two borrowed strings and return the longer one.
longest_reference.rs
fn longest<'a>(left: &'a str, right: &'a str) -> &'a str {
if left.len() >= right.len() { left } else { right }
}
fn main() {
let left = "rust";
let suffix = ;
let winner = longest(left, suffix);
println!("{winner}");
}
fn longest<'a>(left: &'a str, right: &'a str) -> &'a str {
if left.len() >= right.len() { left } else { right }
}
fn main() {
let left = "rust";
let suffix = ;
let winner = longest(left, suffix);
println!("{winner}");
}
fn longest<'a>(left: &'a str, right: &'a str) -> &'a str {
if left.len() >= right.len() { left } else { right }
}
fn main() {
let left = "rust";
let suffix = ;
let winner = longest(left, suffix);
println!("{winner}");
}
lifetime parameter
`'a` names the relationship between input and output references.
borrow return
The function returns one of the borrowed inputs, not a new string.
comparison
The branch decides which borrowed value is returned.