Code Logo

Annotate Lifetimes with 'a

Published at25 Jul 2026
Rust Functions Hard 1 views
Like0

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

Example 1
Input
"a","bb"
Output
"bb"
Explanation

bb is longer

Example 2
Input
"long","short"
Output
short
Explanation

short is longer

Example 3
Input
"hello","world"
Output
hello
Explanation

Equal length, return first (hello)

Example 4
Input
"same","same"
Output
"same"
Explanation

Equal length, return first

Example 5
Input
"rust","is"
Output
"rust"
Explanation

rust is longer

Algorithm Flow

Recommendation Algorithm Flow for Annotate Lifetimes with 'a

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.

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } }

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

rust - Approach 1
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() >= y.len() { x } else { y }
}