error[E0597]: `x` does not live long enough
error: borrowed value does not live long enough
A reference outlives the data it points to. Rustβs borrow checker prevents dangling references.
Fix 1: Return Owned Data Instead of Reference
// β Returning reference to local variable
fn get_name() -> &str {
let name = String::from("Alice");
&name // π₯ name is dropped at end of function
}
// β
Return owned String
fn get_name() -> String {
String::from("Alice")
}
Fix 2: Extend the Lifetime
// β Temporary dropped too soon
let r;
{
let x = 5;
r = &x; // π₯ x dropped here
}
println!("{}", r);
// β
Move x to outer scope
let x = 5;
let r = &x;
println!("{}", r);
Fix 3: Use Clone
// β Borrowing from a temporary
let first = vec!["a", "b", "c"].first(); // π₯ Vec is temporary
// β
Clone the data
let items = vec!["a", "b", "c"];
let first = items.first();
Fix 4: Lifetime Annotations in Structs
// β Struct holds reference but no lifetime
struct Config {
name: &str, // π₯ Missing lifetime
}
// β
Add lifetime annotation
struct Config<'a> {
name: &'a str,
}
Fix 5: Use String Instead of &str in Structs
// β
Owned data β no lifetime needed
struct Config {
name: String, // Owns the data
}
This is often the simplest fix. Use owned types (String, Vec<T>) in structs unless you have a specific reason to borrow.
Related resources
Related: Cargo Cheat Sheet