Annotate Lifetimes with 'a
Write a Rust function with explicit lifetime annotations that takes two string slices and returns the longer one. The function must use a lifetime parameter 'a to indicate that the returned reference is valid as long as both input references are valid.
Lifetime annotations are Rust's mechanism for ensuring that references are always valid. The syntax &'a str declares a reference with lifetime 'a. When a function returns a reference, its lifetime must be connected to the lifetimes of its parameters. The annotation fn longest<'a>(x: &'a str, y: &'a str) -> &'a str tells the compiler that the returned reference lives as long as the shorter of x and y.
Lifetimes are one of Rust's most distinctive and challenging features. They enable the compiler to guarantee memory safety without a garbage collector. The borrow checker uses lifetime information to prevent dangling references, use-after-free, and other memory bugs — all at compile time with zero runtime cost.
Time complexity is O(n + m) where n and m are the string lengths (to compare lengths), but typically O(1) if lengths are compared first. Space complexity is O(1) as the function returns a borrowed reference without allocating.
Edge cases include equal-length strings (return either one), one empty string, both empty, and ensuring the lifetime annotation is correct for strings with different scopes. The compiler will reject the code if lifetimes are incorrectly specified.
Example Input & Output
bb is longer
short is longer
Equal length, return first (hello)
Equal length, return first
rust is longer
Algorithm Flow
Solution Approach
Annotate lifetimes in a function that returns a reference to ensure the reference does not outlive its source data. Lifetimes are denoted with 'a and specify how long references are valid. The function signature links the lifetimes of input references to the output reference.
Lifetime annotations tell the borrow checker that the returned reference lives as long as both inputs. Without annotations, Rust cannot determine the relationship between input and output lifetimes.
Time O(1), Space O(1).
Best Answers
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() >= y.len() { x } else { y }
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
