tl;dr error[E0716]: temporary value dropped while borrowed
is a difficult and common problem, is there a consistent solution?
I've run into the difficult rustc error
error[E0716]: temporary value dropped while borrowed
...
creates a temporary which is freed while still in use
Searching Stackoverflow, there are many questions for this rust error error[E0716]
.
Maybe a rust expert can provide a general solution for this common newbie problem, a solution good enough that it might also Answer the linked Questions (see below).
example code
A concise code sample to demonstrate the problem (rust playground):
type Vec1<'a> = Vec::<&'a String>;
fn fun1(s1: &String, v1: &mut Vec1) {
v1.insert(0, &s1.clone());
}
fn main() {
let mut vec1 = Vec::new();
let str1 = String::new();
fun1(&str1, &mut vec1);
}
result:
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:4:19
|
3 | fn fun1(s1: &String, v1: &mut Vec1) {
| -- has type `&mut Vec<&'1 String>`
4 | v1.insert(0, &s1.clone());
| --------------^^^^^^^^^^-- temporary value is freed at the end of this statement
| | |
| | creates a temporary which is freed while still in use
| argument requires that borrow lasts for `'1`
For more information about this error, try `rustc --explain E0716`.
my understanding
My understanding is given the statement v1.insert(0, &s1.clone());
,
the s1.clone()
would create a new String
using the heap as storage. Then a reference of that newly cloned String
(the added &
) is passed into call v1.insert
. So the new String
data and the reference passed to insert
will remain after the function fun1
returns.
But the rust compiler reports s1.clone()
is merely temporary.
similar linked questions
Here are links to similar Questions, not always the same, version of this Question, but somewhat more cumbersome and verbose (IMO).
- error[E0716]: temporary value dropped while borrowed
- Why is it legal to borrow a temporary?
- temporary value dropped while borrowed
- Temporary value dropped while borrowed (E0506)
- "Temporary value dropped while borrowed" when using string.replace()
- error[E0716]: temporary value dropped while borrowed
- How to solve "temporary value dropped while borrowed"
- Iterator Find, Temporary Value Dropped While Still Borrowed
- "temporary value dropped while borrowed" with capturing closure
- Rust reference dropped here while still borrowed
- Confused by "temporary value dropped here while still borrowed" [duplicate]
- "borrowed value does not live long enough" when using the builder pattern
- Builder pattern - borrowed value does not live long enough
- Unable to compile a Rust builder pattern because a borrowed value does not live long enough [duplicate]
- Borrowed value does not live long enough
I added a Comment on those Questions that links to this Question.