Error E0716

"temporary value dropped while borrowed" — How to Fix

Fix Rust error E0716 by storing the temporary value in a variable or cloning it before borrowing.

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()
}