Sub topic 3
Fixing Lifetime Errors
Assume you know basic Rust syntax, ownership, references, and how to run cargo check. A lifetime is the part of a reference’s type that describes how long the referenced value remains valid.
Missing Lifetime Specifiers
When a function returns one of its input references, Rust needs to know how the output relates to the inputs. This signature is ambiguous:
fn longest(a: &str, b: &str) -> &str {
if a.len() >= b.len() { a } else { b }
}Rust reports E0106, “missing lifetime specifier.” Add one lifetime parameter and use it for both inputs and the result:
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
fn main() {
println!("{}", longest("short", "longer"));
}The function promises that its result cannot outlive the shorter-lived input reference.
Lifetime and Trait Errors
E0597, “does not live long enough,” means a reference would survive the value it points to. Move the value into a scope that lasts long enough, or return owned data instead of a reference.
E0277 means a required trait bound is missing. A trait defines behavior that a type can implement. For example, formatting with {} requires Display. Use {:?} for types that implement Debug, or implement the required trait.
fn main() {
let values = vec![1, 2, 3];
println!("{values:?}");
}A non-exhaustive match produces E0004. Add every variant or use a wildcard when the remaining cases share one result.
enum Light { Red, Yellow, Green }
fn action(light: Light) -> &'static str {
match light {
Light::Red => "stop",
Light::Yellow => "slow down",
Light::Green => "go",
}
}Read Suggestions in Order
Read the error code, message, highlighted span, labels, notes, and help text. Apply a suggestion only when it matches your intent. cargo fix can apply machine-generated changes, but review the diff afterward and run tests.
Minimal Reproductions
For a stubborn error, copy only the smallest function, type, and input that still fails. Remove unrelated crates and application code. This reveals the lifetime or trait relationship and makes help easier to give.
Exercise
What should you do first when cargo check reports errors involving both a lifetime and several later lines?
Show answer
Fix the first diagnostic, then run cargo check again because later errors may be cascading symptoms.