E0716 Temporary Dropped Fix
A value with no name dies at the end of its statement, and E0716 is the compiler refusing to let a borrow point into it past that point. This guide separates the shapes that produce it - a borrow passed through a call, a method borrow of a temporary String or Vec, a borrow wrapped in an Option or a vec, a borrow made in a branch, and a borrow stored in a struct field - and matches each one to the same repair in different clothing: give the value a name, in a binding that outlives the borrow.
Written November 23, 2026 · Tested with Rust 1.99.1 · 29 min read
- The rule underneath: a temporary dies at the end of its statement, unless its lifetime is extended
- How to read the diagnostic
- The first failure: a function result borrowed through a helper call
- The second failure: a temporary String borrowed with asstr
Written November 23, 2026
Tested with Rust 1.99.1
What this guide is
Error E0716 is a lifetime that ends too early. The error codes index defines it in one line: a temporary value is being dropped while a borrow is still in active use. A temporary is the storage the compiler creates for a value that has no name - the return value of a function call, the String built by String::from, the vector built by vec!. That storage is dropped at a fixed point, ordinarily the end of the enclosing statement. When a borrow taken from the temporary is still needed after that point - printed on the next line, stored in a container, returned from a branch - the borrow would point into freed storage, and the compiler reports E0716 instead of allowing it.
The forms in this guide each reproduce E0716 with a small, complete program, and each lets a borrow escape a temporary in a different way. A function result borrowed through a helper that returns the borrow. A temporary String borrowed with as_str. A temporary vector borrowed with first. A borrow wrapped in Some, so the Option carries it past the statement. A borrow collected into a vec!, so the vector carries it. A borrow produced inside an if branch and stored by the surrounding let. And a borrow stored in a struct field. In each family the failing program is small, the full compiler output is shown, and the fix is the same move the error index prescribes: create a local variable to store the value, in a binding whose scope covers every use of the borrow, and borrow from that variable instead.
Several neighboring results are not E0716 and are worked only in the traps and the decision summary. A reference to a temporary bound directly by a let - let r = &String::from("hi");, let r: &[i32] = &vec![1, 2, 3]; - compiles, because lifetime extension moves the temporary's drop to the end of the enclosing block. A temporary in an if let scrutinee lives for the whole body, so borrowing it there compiles. A borrow created and used inside a single statement compiles, because the temporary outlives the statement that uses it. A function that returns a reference with no lifetime to borrow from is E0106. And returning a reference to a named local variable, where a lifetime is declared, is E0515 - the subject of the E0515 guide.
Build every program in this guide with rustc --edition 2021. In the compiler transcripts below, the file names are the bare names shown on the command line.
The rule underneath: a temporary dies at the end of its statement, unless its lifetime is extended
Every value that is not bound to a variable lives in a temporary, and every temporary is associated with a drop scope. The Rust Reference on destructors puts it this way: when a variable or temporary goes out of scope, its destructor is run - it is dropped - and each variable or temporary is associated to a drop scope, with scopes for the entire function, each statement, each expression and each block. For an ordinary expression, the temporary scope is the smallest containing scope among those - in practice, the enclosing statement. The error index states the same rule from the borrower's side: whenever a temporary is created, it is automatically dropped according to fixed rules, and ordinarily the temporary is dropped at the end of the enclosing statement.
A borrow does not extend that scope by itself. String::from("hello").as_str() creates a temporary String, borrows its contents as a &str, and schedules the String for the end of the statement; the &str in the let binding is left pointing at storage that the schedule has already freed. The compiler compares the two lifetimes - the borrow's, which runs to its last use, and the temporary's, which ends at the statement - and E0716 is the report that the second ends first. The neighboring error E0597, covered by the E0597 guide, is the same comparison made against a named variable whose scope is too short; E0716 is the case where the too-short scope belongs to a value that never had a name.
The one exception is lifetime extension, and its limits explain which of this guide's shapes fail and which compile. When a reference expression is stored directly into a variable - the error index's wording is that in simple cases where the & expression is immediately stored into a variable, the compiler will automatically extend the lifetime of the temporary until the end of the enclosing block - and the same applies when such references are stored directly into an aggregate such as a tuple or a struct. So let r = &foo(); compiles: the temporary behind the reference lives as long as a local variable would. But extension reaches only the reference expression itself, in the positions the rule names. It does not reach a borrow that a function returns (bar(&foo())) or a borrow a method produces (temp.as_str(), temp.first()) - not even when that method borrow is passed through a constructor call (Some(...)) or a macro (vec![...]), produced in one branch of an if, or - the subtle one - stored in a struct field: the struct literal is an aggregate, but the field holds the result of as_str(), not a & expression, so there is nothing for extension to act on. The positions are not what blocks extension - a plain & expression in the same positions is extended, as Some(&String::from("hi")) and an if whose arms are &String::from("a") and &String::from("b") both compile - what blocks it is that the stored value is a method's or a function's result rather than a & expression. Each of those is a family below.
The fix follows from the rule rather than from the diagnostic's wording. A named variable declared with let is dropped at the end of the enclosing block, not at the end of its statement, so binding the temporary first - let value = foo();, let s = String::from("hello"); - gives the borrow a scope that covers it, and borrowing from the variable creates no temporary at all. The binding must be declared before the borrow and in a scope that contains every use of the borrow; a binding declared inside a smaller block than the borrow's uses trades E0716 for the same problem one scope out.
How to read the diagnostic
The header is constant across the whole family: "temporary value dropped while borrowed". The span work below it carries the specifics, in three parts. The caret span marks the expression that creates the temporary - &foo(), String::from("hello"), vec![1, 2, 3] - annotated "creates a temporary value which is freed while still in use". A second marker on the same line states when the storage dies: "temporary value is freed at the end of this statement". And a third marker points at the surviving borrow - "borrow later used here", or, where the borrow is stored rather than used directly, "borrow later stored here". Reading the three together gives the whole defect: what the temporary is, when it dies, and which borrow outlives it.
The help, when it appears, is the fix in outline: "consider using a let binding to create a longer lived value", with a rewrite that hoists the temporary into a binding named binding and borrows from it. That rewrite is reliable in this error family - it is the repair the error index itself prescribes - and the fixes below differ from it only in the name chosen for the binding. One family below, the if branch, prints the same sentence as a note rather than a help with a rewrite, because the value to hoist sits inside a branch; the repair is unchanged. When no help appears at all and the header names a different code, the program belongs to the traps, not to this family.
The first failure: a function result borrowed through a helper call
This is the error index's own example shape. &foo() borrows the return value of foo(), which has no name, so it lands in a temporary; bar returns that borrow, and the let stores the borrow - not the value - so nothing extends the temporary's life, and it is freed at the end of the statement while p is still to be printed:
fn foo() -> i32 { 22 }
fn bar(x: &i32) -> &i32 { x }
fn main() { let p = bar(&foo()); println!("{}", p); }
$ rustc --edition 2021 fail_fn_arg.rs -o fail_fn_arg
error[E0716]: temporary value dropped while borrowed
--> fail_fn_arg.rs:3:26
|
3 | fn main() { let p = bar(&foo()); println!("{}", p); }
| ^^^^^ - - borrow later used here
| | |
| | temporary value is freed at the end of this statement
| creates a temporary value which is freed while still in use
|
help: consider using a `let` binding to create a longer lived value
|
3 ~ fn main() { let binding = foo();
4 ~ let p = bar(&binding); println!("{}", p); }
|
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0716`.
The contrast to keep is with let p = &foo(); in the traps: there the & expression itself is what the let stores, so extension applies. Here the let stores the result of bar(...) - a borrow one call removed from the temporary - and extension does not follow it through the call. The fix binds the value first, so bar borrows a variable:
fn foo() -> i32 { 22 }
fn bar(x: &i32) -> &i32 { x }
fn main() { let value = foo(); let p = bar(&value); println!("{}", p); }
$ rustc --edition 2021 fix_fn_arg.rs -o fix_fn_arg
$ ./fix_fn_arg
22
The output is 22, the value foo returned. Any helper that returns a borrow of its argument - an identity function, a getter, a selector - has the same property: the caller's value must have a name before it goes in.
The second failure: a temporary String borrowed with as_str
String::from("hello") builds a String that nothing names. as_str borrows that temporary's contents, and the let stores the borrow; the String itself is freed at the end of the statement, before the println! that uses the borrow:
fn main() { let r = String::from("hello").as_str(); println!("{}", r); }
$ rustc --edition 2021 fail_as_str.rs -o fail_as_str
error[E0716]: temporary value dropped while borrowed
--> fail_as_str.rs:1:21
|
1 | fn main() { let r = String::from("hello").as_str(); println!("{}", r); }
| ^^^^^^^^^^^^^^^^^^^^^ - - borrow later used here
| | |
| | temporary value is freed at the end of this statement
| creates a temporary value which is freed while still in use
|
help: consider using a `let` binding to create a longer lived value
|
1 ~ fn main() { let binding = String::from("hello");
2 ~ let r = binding.as_str(); println!("{}", r); }
|
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0716`.
Method calls are the everyday source of this error, because a method borrow looks like a conversion: as_str, as_bytes, as_slice and their kin produce a borrow of the receiver, so chaining one onto a value built in the same expression borrows a temporary. Lifetime extension does not apply - the expression the let stores is the method's result, not a & expression. The fix gives the String a name and borrows from the name:
fn main() { let s = String::from("hello"); let r = s.as_str(); println!("{}", r); }
$ rustc --edition 2021 fix_as_str.rs -o fix_as_str
$ ./fix_as_str
hello
The output is hello. The same repair applies to format!(...) results, file contents read in a chain, and any other owned value built and borrowed in one expression: split the expression at the ownership boundary, build first, borrow second.
The third failure: a temporary vector borrowed with first
first returns a borrow of an element - here an Option<&i32> - so calling it on a vector built in the same expression stores a borrow of a temporary vector. The vector is freed at the end of the statement; the Option that carries the borrow is not:
fn main() { let f = vec![1, 2, 3].first(); println!("{:?}", f); }
$ rustc --edition 2021 fail_first.rs -o fail_first
error[E0716]: temporary value dropped while borrowed
--> fail_first.rs:1:21
|
1 | fn main() { let f = vec![1, 2, 3].first(); println!("{:?}", f); }
| ^^^^^^^^^^^^^ - - borrow later used here
| | |
| | temporary value is freed at the end of this statement
| creates a temporary value which is freed while still in use
|
help: consider using a `let` binding to create a longer lived value
|
1 ~ fn main() { let binding = vec![1, 2, 3];
2 ~ let f = binding.first(); println!("{:?}", f); }
|
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0716`.
The shape generalizes past first: last, get, indexing, iter, and a slice conversion such as as_slice all borrow the receiver, so any of them chained onto a vec! - or onto a function call returning a vector, or a collect - is this family. What the borrow points into is the whole temporary collection, not just the element, so the collection is the value that needs the name. The fix binds the vector:
fn main() { let v = vec![1, 2, 3]; let f = v.first(); println!("{:?}", f); }
$ rustc --edition 2021 fix_first.rs -o fix_first
$ ./fix_first
Some(1)
The output is Some(1), the first element as an Option. Where only the element's value is needed and no borrow has to survive, copying it out - copied() on the Option, or a match that moves the value - is the other honest repair; where the borrow itself is the value being kept, the binding is the repair.
The fourth failure: a borrow wrapped in Some
Wrapping a method-produced borrow in a constructor does not extend the borrowed-from value's life. Some(...) is a function call - the variant's constructor - and the value it carries here is the result of as_str(), not a & expression, so nothing in the stored Option<&str> is extended, and its borrow points into a String temporary that the statement's end frees:
fn main() { let a = Some(String::from("hi").as_str()); println!("{:?}", a); }
$ rustc --edition 2021 fail_option_wrap.rs -o fail_option_wrap
error[E0716]: temporary value dropped while borrowed
--> fail_option_wrap.rs:1:26
|
1 | fn main() { let a = Some(String::from("hi").as_str()); println!("{:?}", a); }
| ^^^^^^^^^^^^^^^^^^ - - borrow later used here
| | |
| | temporary value is freed at the end of this statement
| creates a temporary value which is freed while still in use
|
help: consider using a `let` binding to create a longer lived value
|
1 ~ fn main() { let binding = String::from("hi");
2 ~ let a = Some(binding.as_str()); println!("{:?}", a); }
|
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0716`.
This family is where the aggregate wording of the extension rule misleads. Extension does cover references stored directly into an aggregate - let value = (&foo(), &foo()); compiles, as the error index shows - but the field here is not a & expression stored into the aggregate; it is a method call's result passed through a constructor function. The temporary String is an argument's receiver, two steps removed from the stored value, and extension reaches neither step. Ok(...), Err(...), a tuple-struct constructor, and any ordinary function that stores or returns the borrow behave the same way. The fix binds the String before the wrap:
fn main() { let owned = String::from("hi"); let a = Some(owned.as_str()); println!("{:?}", a); }
$ rustc --edition 2021 fix_option_wrap.rs -o fix_option_wrap
$ ./fix_option_wrap
Some("hi")
The output is Some("hi"). The binding's name in the fix, owned, states the relationship the type leaves implicit: the Option borrows, and something named must own.
The fifth failure: a borrow collected into a vec
A vec! literal is a macro that builds a vector from its elements; storing a borrow as an element stores it in a container that outlives the statement, while the borrowed-from String remains a temporary of that statement:
fn main() { let v = vec![String::from("hi").as_str()]; println!("{:?}", v); }
$ rustc --edition 2021 fail_vec_wrap.rs -o fail_vec_wrap
error[E0716]: temporary value dropped while borrowed
--> fail_vec_wrap.rs:1:26
|
1 | fn main() { let v = vec![String::from("hi").as_str()]; println!("{:?}", v); }
| ^^^^^^^^^^^^^^^^^^ - - borrow later used here
| | |
| | temporary value is freed at the end of this statement
| creates a temporary value which is freed while still in use
|
help: consider using a `let` binding to create a longer lived value
|
1 ~ fn main() { let binding = String::from("hi");
2 ~ let v = vec![binding.as_str()]; println!("{:?}", v); }
|
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0716`.
A container changes nothing about the temporary's schedule - it only gives the borrow somewhere longer-lived to sit, which is exactly what makes the defect visible: without the vector, the borrow would have died with the statement and no error would be needed. Arrays, tuples built from method borrows, HashMap inserts, and a push of a borrow taken from a value built in the same statement are the same family. The fix binds the borrowed-from value before the container is built:
fn main() { let owned = String::from("hi"); let v = vec![owned.as_str()]; println!("{:?}", v); }
$ rustc --edition 2021 fix_vec_wrap.rs -o fix_vec_wrap
$ ./fix_vec_wrap
["hi"]
The output is ["hi"], the vector holding the one borrow. When a container holds several borrows, every borrowed-from value needs its own binding, and all of them must live in a scope that contains the container's last use.
The sixth failure: a borrow produced in an if branch
An if expression used as a let initializer produces its value from a branch, and a borrow produced inside the branch points into the branch's own temporary. The String built in the if arm is freed at the end of the statement that contains the whole expression, while the &str the let stored is used afterward:
fn main() { let r = if true { String::from("a").as_str() } else { "b" }; println!("{}", r); }
$ rustc --edition 2021 fail_if_else.rs -o fail_if_else
error[E0716]: temporary value dropped while borrowed
--> fail_if_else.rs:1:31
|
1 | fn main() { let r = if true { String::from("a").as_str() } else { "b" }; println!("{}", r); }
| - ^^^^^^^^^^^^^^^^^ - temporary value is freed at the end of this statement
| | |
| | creates a temporary value which is freed while still in use
| borrow later stored here
|
= note: consider using a `let` binding to create a longer lived value
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0716`.
Two details separate this family from the others. The diagnostic's third marker reads "borrow later stored here" rather than "borrow later used here", because the borrow's fault is being stored by the let, out of the branch that owns its referent. And the repair sentence arrives as a note, with no rewritten lines, because the value to hoist is inside a branch - the compiler names the move without performing it. The asymmetry between the arms is what hides the defect in real code: the else arm's "b" is a string literal with no owner to free, so only the arm that builds its value can fail. A match arm that builds and borrows behaves identically. The fix hoists the built value above the if, so both arms borrow from storage that outlives the expression - the literal arm needs nothing, and the built arm borrows the binding:
fn main() { let owned = String::from("a"); let r = if true { owned.as_str() } else { "b" }; println!("{}", r); }
$ rustc --edition 2021 fix_if_else.rs -o fix_if_else
$ ./fix_if_else
a
The output is a, the branch taken. Hoisting changes when the value is built - before the branch rather than inside it - but not what either arm yields, which is the sense in which every fix in this guide preserves the program's meaning.
The seventh failure: a borrow stored in a struct field
A struct literal is an aggregate, and the extension rule names aggregates - but it extends temporaries behind & expressions stored into them, and this field stores the result of as_str(), a borrow of a String temporary that the literal does not own. The struct outlives the statement; the String does not:
struct Holder<'a> { s: &'a str }
fn main() { let h = Holder { s: String::from("hi").as_str() }; println!("{}", h.s); }
$ rustc --edition 2021 fail_struct_field.rs -o fail_struct_field
error[E0716]: temporary value dropped while borrowed
--> fail_struct_field.rs:2:33
|
2 | fn main() { let h = Holder { s: String::from("hi").as_str() }; println!("{}", h.s); }
| ^^^^^^^^^^^^^^^^^^ - --- borrow later used here
| | |
| | temporary value is freed at the end of this statement
| creates a temporary value which is freed while still in use
|
help: consider using a `let` binding to create a longer lived value
|
2 ~ fn main() { let binding = String::from("hi");
3 ~ let h = Holder { s: binding.as_str() }; println!("{}", h.s); }
|
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0716`.
The contrast is exact: Holder { s: &String::from("hi") } would put a & expression in the field and extension would apply, while Holder { s: String::from("hi").as_str() } puts a method result there and it does not - one token's difference in form, opposite outcomes, because extension is a rule about the shape of the stored expression, not about the programmer's intent. Structs that hold borrows - views, cursors, parsed records - meet this family whenever the viewed value is built at the construction site. The fix binds the viewed value first, in the same scope as the struct:
struct Holder<'a> { s: &'a str }
fn main() { let owned = String::from("hi"); let h = Holder { s: owned.as_str() }; println!("{}", h.s); }
$ rustc --edition 2021 fix_struct_field.rs -o fix_struct_field
$ ./fix_struct_field
hi
The output is hi, read back out of the field. The declaration order in the fix is the lifetime made visible: owned is declared before h, so it is dropped after h, and the field's borrow is valid for the struct's whole life.
The fixes in reach order
- The borrow came back out of a helper call that took
&temporary: a function result borrowed through a call - bind the result first, then pass&bindingin. - The stored expression is a method call on a value built in the same expression -
temp.as_str(),temp.as_bytes(): a method borrow of a temporary - bind the built value, then call the method on the binding. - The stored expression borrows an element or slice of a collection built in the same expression -
vec![...].first(): bind the collection, then borrow from it. - The borrow is wrapped in
Some,Ok, or another constructor: wrapping a method-produced borrow does not extend it - a constructor argument is extended only when the argument is itself a&expression, as inSome(&temp())- so bind the borrowed-from value before the wrap. - The borrow is an element of a
vec!, an array, or another container being built: bind every borrowed-from value before building the container. - The borrow is produced in an
iformatcharm and stored by the surroundinglet: hoist the built value above the expression, so the arm borrows a binding instead of its own temporary. - The borrow sits in a struct or tuple field and its value is a method result: bind the value before the literal - extension covers a
&expression in the field, not a method borrow. - In every case: the binding goes in a scope that contains the borrow's last use, declared before the borrow - a binding in a smaller scope than the borrow is the same error one level out.
Traps
- A reference to a temporary bound directly by a
letcompiles - it is not an E0716 family. Lifetime extension moves the temporary's drop from the end of the statement to the end of the enclosing block when the&expression is itself the stored value:
fn main() { let r: &[i32] = &vec![1, 2, 3]; println!("{:?}", r); }
$ rustc --edition 2021 probe_let_ref_vec.rs -o probe_let_ref_vec
$ ./probe_let_ref_vec
[1, 2, 3]
[1, 2, 3]. This is the same temporary vector as the third family with the borrow taken one way rather than another: &vec![...] stored directly is extended, vec![...].first() is a method result and is not. The Reference on destructors states the general rule - apart from lifetime extension, the temporary scope of an expression is the smallest containing scope among the function, a statement, an if body, and the other listed scopes - and this trap is the "apart from" clause at work.
- A direct reference to a temporary String compiles for the same reason. &String::from("hi") is a & expression stored into the binding, so the temporary String lives until the end of the block:fn main() { let r = &String::from("hi"); println!("{}", r); }
$ rustc --edition 2021 probe_let_ref_string.rs -o probe_let_ref_string
$ ./probe_let_ref_string
hi
The output is hi. Compare the second family, where String::from("hello").as_str() fails: the two programs differ only in whether the stored expression is the reference itself or a borrow returned by a method, and that difference is the whole of the extension rule's reach. Do not "fix" the direct form by hoisting it - it is already the extended form, and hoisting is a no-op rewrite.
- A temporary in an if let scrutinee lives for the whole body, so borrowing it there compiles. The scrutinee's temporary scope covers the pattern-matching condition and the consequent body - the Reference lists the pattern-matching condition(s) and consequent body of if among the temporary scopes - so a borrow taken from the scrutinee is still inside the temporary's life while the body runs:
fn main() { if let Some(s) = Some(String::from("hi").as_str()) { println!("{}", s); } }
$ rustc --edition 2021 probe_if_let_scrutinee.rs -o probe_if_let_scrutinee
$ ./probe_if_let_scrutinee
hi
The output is hi. Compare the fourth family: the same Some(...) expression fails when a let stores it, because the borrow must then survive the statement, and compiles here, where every use of the borrow sits inside the scrutinee's scope. The deciding question is never the shape of the expression alone - it is whether the borrow's last use falls inside or outside the temporary's scope. A match scrutinee behaves the same way for its arms.
- A borrow created and used inside a single statement compiles. The temporary is freed at the end of the statement, and a use inside that same statement is before the free, not after it:
fn main() { println!("{}", String::from("hello").as_str()); }
$ rustc --edition 2021 probe_same_statement.rs -o probe_same_statement
$ ./probe_same_statement
hello
The output is hello. This is the second family's program with the let removed: nothing stores the borrow, so nothing outlives the temporary, and there is no defect to report. Most chained borrows in real code are of this kind and are correct as written - E0716 begins exactly where the borrow is given a name, a container, or a return path that carries it past the semicolon.
- A function returning a reference with no lifetime to borrow from is E0106, not E0716. There is no temporary in the caller's statement here at all - the signature itself promises a borrow without naming anything it could be borrowed from, and the compiler stops at the signature:
fn f() -> &i32 { &42 }
fn main() { println!("{}", f()); }
$ rustc --edition 2021 probe_return_no_lifetime.rs -o probe_return_no_lifetime
error[E0106]: missing lifetime specifier
--> probe_return_no_lifetime.rs:1:11
|
1 | fn f() -> &i32 { &42 }
| ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider using the `'static` lifetime, but this is uncommon unless you're returning a borrowed value from a `const` or a `static`
|
1 | fn f() -> &'static i32 { &42 }
| +++++++
help: instead, you are more likely to want to return an owned value
|
1 - fn f() -> &i32 { &42 }
1 + fn f() -> i32 { &42 }
|
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0106`.
The header reads "missing lifetime specifier", and the error codes index defines E0106 as a lifetime specifier missing in a type or a function signature. Programmers reaching for "return a reference to a temporary" usually write this shape first and meet E0106 before E0716 is reachable - the subject of the E0106 guide.
- Returning a reference to a named local is E0515, not E0716. Once the signature declares a lifetime, returning &y - a borrow of a variable owned by the function - is reported as returning a reference to a local, because y is a named variable with a function scope, not a statement temporary:
fn f<'a>(x: &'a i32) -> &'a i32 { let y = *x + 41; &y }
fn main() { let z = 1; println!("{}", f(&z)); }
$ rustc --edition 2021 probe_return_local_e0515.rs -o probe_return_local_e0515
error[E0515]: cannot return reference to local variable `y`
--> probe_return_local_e0515.rs:1:52
|
1 | fn f<'a>(x: &'a i32) -> &'a i32 { let y = *x + 41; &y }
| ^^ returns a reference to data owned by the current function
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0515`.
The header reads "cannot return reference to local variable y". The boundary between the two codes is the referent's kind: a temporary dropped at a statement's end draws E0716, a named local dropped at its function's end draws E0515 - the subject of the E0515 guide. Neither is repaired by a caller's let binding; the E0515 repair is to return the owned value, or a borrow of something the caller supplied.
Decision summary
- The header says "temporary value dropped while borrowed" and the temporary is a function result borrowed through a helper (E0716): bind the result, then pass the borrow.
- The header says the same and the stored expression is a method borrow of a value built in that expression -
as_str,first,as_slice(E0716): bind the built value or collection, then borrow from the binding. - The header says the same and the borrow is wrapped in a constructor, collected into a container, produced in a branch, or stored in a struct field (E0716): bind the borrowed-from value before the wrap, the container, the branch, or the literal.
- The diagnostic's third marker says "borrow later stored here" (E0716): the branch-produced case - hoist the value above the
iformatch. - A direct
letof a reference to a temporary -let r = &temp;,let r: &[i32] = &vec![...];- compiles: no error - lifetime extension gives the temporary the enclosing block's scope. - A borrow of a scrutinee temporary inside an
if letormatchbody compiles: no error - the scrutinee's temporary scope covers the body. - A borrow created and consumed inside one statement compiles: no error - the use precedes the end-of-statement drop.
- The header says "missing lifetime specifier" at a return type (E0106): the signature promises a borrow from nothing - the subject of the E0106 guide.
- The header says "cannot return reference to local variable" (E0515): a named local, not a temporary - return the owned value instead, the subject of the E0515 guide.
- The header says a variable "does not live long enough" (E0597): the referent is a named variable whose block ends too early - move or widen that binding, the subject of the E0597 guide.
- The header says a value "cannot be moved out of because it is borrowed" (E0505) or "cannot be used because it is mutably borrowed" (E0503): a move or use conflicts with a live borrow - a different defect from the referent's scope ending, the subjects of the E0505 guide and the E0503 guide.
Checklist
- The temporary identified from the caret span: the function call, constructor, or macro whose result has no name - that value, not the borrow, is what needs the binding.
- The borrow's last use located: the binding's scope must contain it - declared earlier in the same block at minimum, and in an enclosing block when the borrow is stored or returned from an inner one.
- The value bound with
letbefore the borrow is taken, and the borrow taken from the binding - never from a fresh call, constructor, or literal in the borrowing expression. - No reliance on lifetime extension outside its reach: it covers a
&expression stored directly, stored directly into a tuple or struct, passed as a constructor's argument, or placed as a branch's arm expression - never a method result or a call's return, wherever that result is stored. - Constructors, containers, branches and fields checked as storage, not as shelter: wrapping a borrow in
Some, avec, anif, or a struct moves the borrow past the statement and changes nothing about the referent's drop. - Scrutinee and same-statement borrows left alone: a borrow whose uses all sit inside the temporary's scope is correct code, and hoisting it is churn.
- A returned reference checked for its own codes first: no lifetime in the signature is E0106, a named local behind the reference is E0515 - neither is fixed at the call site.
- After the binding is introduced, the program compiled again and run: the fix is finished only when the borrow reads the value the program built and the output is the value the program was written to produce.
Related guides on this site
- E0506 Assign While Borrowed Fix
- E0503 Cannot Use Fix
- E0505 Cannot Move Out Fix
- Fix Rust E0502 "cannot borrow as mutable because it is also borrowed as immutable" — End the First Borrow, Split the Work, or Restructure
Sources
- Rust, Error codes index: E0716 - the definition of the error: a temporary value is being dropped while a borrow is still in active use - with the
bar(&foo())example, the rule that a temporary is ordinarily dropped at the end of the enclosing statement, the fix of creating a local variable to store the value, and the lifetime-extension cases: a&expression immediately stored into a variable, and temporaries stored directly into aggregate structures like a tuple or a struct. - The Rust Reference, Destructors - when a variable or temporary goes out of scope its destructor is run; each variable or temporary is associated to a drop scope, with scopes for the entire function, each statement, each expression and each block; and the temporary scope of an expression - apart from lifetime extension, the smallest containing scope among the function, a statement, the body of an
if,whileorloop, amatcharm, and the pattern-matching conditions and consequent body of anif let. - Rust, Error codes index: E0106 - the neighboring signature error: a lifetime specifier was missing in a type or a function signature - the code a returned reference with nothing to borrow from produces.
- Rust, Error codes index: E0515 - the neighboring return error: a reference to a local variable or a temporary created in a function cannot be returned - the code returning a named local's reference produces, where the referent is a variable rather than a statement temporary.
Keep Exploring
The full Rust hub \u2014 ownership, structs and enums, async, and measured comparisons.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.