Fix the error by cloning the temporary value or storing it in a variable before borrowing it. The compiler stops you from borrowing a value that will be dropped at the end of the statement.
fn main() {
let s = String::from("hello");
let len = calculate_length(&s);
println!("The length of '{s}' is {len}.");
}
fn calculate_length(s: &String) -> usize {
s.len()
}
If you must use a temporary directly, clone it first:
fn main() {
let len = calculate_length(&String::from("hello").clone());
println!("The length is {len}.");
}
fn calculate_length(s: &String) -> usize {
s.len()
}