2026-09-01
This seemingly unsuspicious code:
fn main() {
let s = String::from("hello").as_str();
println!("{}", s);
}
will exhibit an error on compilation:
error[E0716]: temporary value dropped while borrowed
The combination of three circumstances is responsible for this:
as_str(&self) -> &strs (i.e. tries to persist the value beyond the end of the statement)Due to Rust's lifetime rules for returned references, the returned &str will live as long as &self (elision rule no. two or three, pick one), which in turn lives as long as self (the string "hello"), which is not bound to any variable and thus is dropped from memory when control reaches the end of the statement. Then, by rule of transitivity s would be bound to a reference to deallocated memory when executing the next statement.
More generally speaking:
Whenever you call an associated function with a signature of
my_borrowing_method(&self, ...) -> &SomeTypeon a reference of a value that is not bound to a variable (i.e. is a temporary value) and try to bind it beyond the statement that exercises the call you will get the E0716 error.