The E0621 error occurs because the compiler cannot infer a lifetime for a reference returned from a function or stored in a struct, so you must explicitly annotate the lifetime parameter on the function signature or struct definition. This usually happens when returning a reference to data owned by the function's arguments or when a struct holds a reference without specifying how long that reference is valid.
To fix this, add a lifetime parameter (like 'a) to the function or struct and bind it to the input references and the output reference. This tells the compiler that the returned reference lives as long as the input data.
Here is a common scenario where this error appears and how to resolve it:
// ❌ This causes E0621: compiler doesn't know how long the returned &str lives
fn get_first_word(text: &str) -> &str {
let words: Vec<&str> = text.split_whitespace().collect();
words[0]
}
// ✅ Fix: Add lifetime 'a to bind input and output
fn get_first_word<'a>(text: &'a str) -> &'a str {
let words: Vec<&'a str> = text.split_whitespace().collect();
words[0]
}
If you are defining a struct that holds a reference, you must also annotate the struct fields with the lifetime parameter:
// ❌ E0621: lifetime of `name` is unknown
struct User {
name: &str,
}
// ✅ Fix: Annotate the struct and the field
struct User<'a> {
name: &'a str,
}
fn create_user<'a>(name: &'a str) -> User<'a> {
User { name }
}
In modern Rust (edition 2021+), you can often omit the explicit 'a in the function signature if the pattern is simple (one input reference, one output reference), relying on the "elision rules." However, if the compiler still complains, explicitly writing the lifetime is the most reliable solution. The key is ensuring that every reference in the return type or struct field has a corresponding lifetime parameter that matches the scope of the data it points to.