Code Logo

Annotate Lifetimes with 'a

Published at25 Jul 2026
Rust Functions Hard 0 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
Recommendation Algorithm Flow for Annotate Lifetimes with 'a

Solution Approach

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

Best Answers

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