Fix E0597 by ensuring the variable you are borrowing lives long enough to be used after the scope where it is created ends. Move the variable declaration outside the inner scope or return the data instead of a reference to a temporary value.
fn main() {
let data = String::from("hello");
let s = &data; // 's' borrows 'data', which lives for the whole main function
println!("{s}");
}
If you are trying to return a reference to a local variable, you must return the owned value instead:
fn main() {
let s = String::from("hello");
let result = get_string(s); // Pass ownership, not a reference
println!("{result}");
}
fn get_string(s: String) -> String {
s // Return the owned String
}
If you need a reference that lives longer, declare the variable in the outer scope:
fn main() {
let data = String::from("hello");
let s;
{
s = &data; // 's' borrows 'data', which is defined outside this block
}
println!("{s}");
}