Fix Rust E0515 "cannot return value referencing local variable" — a Local String, a Local Number, a Local Vec Slice, and a Struct Wrapping a Local
A function creates a value, returns a reference to it, and the value is dropped on the way out — so the reference would point at nothing. This guide separates the four shapes that produce E0515 — a local String, a local number, a slice of a local Vec, and a struct wrapping a local — and matches each one to returning the owned value, borrowing caller-owned input instead, or letting the caller create the value.
Written November 22, 2026 · Tested with Rust 1.99.0 · 15 min read
- The rule underneath: a function's locals are dropped when it returns
- How to read the diagnostic
- The first failure: returning a reference to a local String
- The second failure: returning a reference to a local number
Written November 22, 2026
Tested with Rust 1.99.0
What this guide is
Error E0515 is a function returning a reference to its own local. The error codes index states the cause in one line: a reference to a local variable was returned. The guarantee behind it comes from the Rust Book chapter on references and borrowing: references must always be valid, and the compiler guarantees that references will never be dangling references, so a function cannot hand back a pointer to a value that its own return destroys.
The four forms in this guide each reproduce E0515 with a small, complete program. A function that builds a String and returns a reference to it. A function that computes a number and returns a reference to the local holding it. A function that builds a Vec and returns a slice of it. And a function that wraps a local in a struct whose field is a reference, and returns the struct. In each family the failing program is small, the full compiler output is shown, and the fix keeps the intent of the code while making sure whatever the caller receives is still alive when the caller uses it.
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 function's locals are dropped when it returns
Local variables, function parameters and temporaries are all dropped before the end of the function body — that is the error index's own summary of this error. A reference to one of those values therefore has nothing valid to point at in the caller: the referent's life ends at the return, and the reference's use would begin after it. E0515 is the compiler reporting that mismatch at the return expression itself, rather than at a later use.
That is why writing a lifetime on the signature cannot rescue a local. The four failing programs below promise 'static — the longest lifetime there is — and still fail, because no annotation changes when a local is dropped. As the Rust Book chapter on lifetime syntax puts it, lifetime annotations describe the relationships of lifetimes to each other without affecting how long any value lives. A lifetime earns its place in the fixes only when the returned reference points at something the caller owns: then the annotation states a true relationship, between the input reference and the returned one.
Every fix in this guide therefore changes what crosses the return boundary, in one of three ways. Return the owned value, so ownership moves to the caller and nothing is dropped. Return a reference to caller-owned input, so the referent lives in the caller's scope and outlives the call. Or restructure so the caller creates the value and passes a reference in, and the function only borrows what it is given.
How to read the diagnostic
Two wordings of the same header appear in this guide, and the difference between them is informative. "cannot return reference to local variable" names a plain reference return: the return expression is &x itself. "cannot return value referencing local variable" names a derived value: a slice of a local, or a struct holding a reference to a local — the returned thing is not itself a reference, but something inside it references the local. The error index makes the same distinction: a returned reference, or a struct containing a reference, to a dropped value would immediately be invalid.
Under the header, the diagnostic underlines the return expression and labels it "returns a reference to data owned by the current function" — or, in the derived cases, adds "v is borrowed here" / "x is borrowed here" pointing at the exact subexpression that borrows the local. That label is the whole diagnosis: the data is owned by the current function, so it dies with the function. The fix follows from what the caller actually needs. If the caller needs the value, return it owned. If the caller already owns a suitable value, borrow that one instead. If neither holds yet, move the creation into the caller so the second fix becomes available.
The first failure: returning a reference to a local String
This is the classic shape, the function form of the Book's dangling-reference example. make_label builds a String, returns &s, and promises 'static in the signature. The promise cannot be kept: s is dropped when the function returns, so the reference the caller receives would point at a deallocated String:
fn make_label() -> &'static String {
let s = String::from("hello");
&s
}
fn main() {
let label = make_label();
println!("{label}");
}
$ rustc --edition 2021 fail_string.rs -o fail_string
error[E0515]: cannot return reference to local variable `s`
--> fail_string.rs:3:5
|
3 | &s
| ^^ 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 signature is where the temptation sits — 'static looks like the strongest thing a return type can say. It is also irrelevant here: 'static describes how long a referent must live, and this referent lives until the closing brace of its own function. The Book's solution to its version of this shape is to return the String directly, and it is the fix here too — ownership moves out to the caller, and nothing is deallocated:
fn make_label() -> String {
let s = String::from("hello");
s
}
fn main() {
let label = make_label();
println!("{label}");
}
$ rustc --edition 2021 fix_string.rs -o fix_string
$ ./fix_string
hello
The output is the text the failing program was trying to hand back. The caller now owns the String and can keep it, lend it, or drop it on its own schedule; there is no borrow left whose referent can die early.
The second failure: returning a reference to a local number
The same mismatch with the smallest possible referent. make_number computes 42 into a local and returns &x. That the value is a plain integer changes nothing: the reference, not the number, is the problem, because the local holding the number is dropped at the return like any other local:
fn make_number() -> &'static i32 {
let x = 42;
&x
}
fn main() {
let n = make_number();
println!("{n}");
}
$ rustc --edition 2021 fail_number.rs -o fail_number
error[E0515]: cannot return reference to local variable `x`
--> fail_number.rs:3:5
|
3 | &x
| ^^ 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`.
Numbers invite a shortcut thought — that something this small and copyable should be exempt. The rule is about the reference's validity, not the value's size, and the diagnostic is the first family's again, changed only in the file name and the variable name.. The fix is also the same shape, and cheaper here than anywhere: return the number itself. An i32 is copied to the caller, no allocation and no borrow are involved, and the caller gets exactly the value the function computed:
fn make_number() -> i32 {
let x = 42;
x
}
fn main() {
let n = make_number();
println!("{n}");
}
$ rustc --edition 2021 fix_number.rs -o fix_number
$ ./fix_number
42
The printed 42 is the value the failing program computed. When the computed thing is small and copyable, the owned return is not merely the safe fix but the natural one — a reference to a fresh local is never the right way to hand a caller a number.
The third failure: returning a slice of a local Vec
Here the returned value is derived from the local rather than being a reference to it directly, and the header wording changes to match. first_two builds a Vec, takes a slice of its first two elements, and returns that slice. The slice is a view into the Vec's storage; when the function returns and the Vec is dropped, the storage is gone and the view points at freed memory:
fn first_two() -> &'static [i32] {
let v = vec![1, 2, 3];
&v[..2]
}
fn main() {
let s = first_two();
println!("{:?}", s);
}
$ rustc --edition 2021 fail_slice.rs -o fail_slice
error[E0515]: cannot return value referencing local variable `v`
--> fail_slice.rs:3:5
|
3 | &v[..2]
| ^-^^^^^
| ||
| |`v` is borrowed here
| returns a value referencing data owned by the current function
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0515`.
The diagnostic separates the two halves of the defect: "v is borrowed here" under the indexing expression, and "returns a value referencing data owned by the current function" under the whole return. A slice return is a legitimate and common shape, though — when the collection belongs to the caller. The fix moves the Vec's creation into main and makes the function borrow it: the signature takes &'a [i32] and returns &'a [i32], stating that the returned slice lives exactly as long as the caller's collection does:
fn first_two<'a>(v: &'a [i32]) -> &'a [i32] {
&v[..2]
}
fn main() {
let v = vec![1, 2, 3];
let s = first_two(&v);
println!("{:?}", s);
}
$ rustc --edition 2021 fix_slice.rs -o fix_slice
$ ./fix_slice
[1, 2]
The output is the two-element slice the failing program was trying to produce, now a view of a Vec that is still alive in main at the print. This is the one family where returning a reference is the right answer rather than a compromise: the function never needed to own a collection, it only needed to select from one, and the lifetime annotation states the true relationship the local version could not satisfy. Where the signature has exactly one input reference, the lifetime elision rules can supply that relationship without the annotation being written — the second elision rule assigns the single input lifetime to the output — but the explicit form above states the contract where a reader can see it.
The fourth failure: returning a struct that wraps a local
The error index names this shape explicitly alongside the plain reference: a struct containing a reference to a dropped value is the same defect one level of indirection away. Wrapper holds a &'a i32; make_wrapper creates the number inside itself, stores a reference to it in the field, and returns the struct promising 'static. The struct crosses the return boundary intact — and its field points at a local that no longer exists:
struct Wrapper<'a> {
value: &'a i32,
}
fn make_wrapper() -> Wrapper<'static> {
let x = 7;
Wrapper { value: &x }
}
fn main() {
let w = make_wrapper();
println!("{}", w.value);
}
$ rustc --edition 2021 fail_wrapper.rs -o fail_wrapper
error[E0515]: cannot return value referencing local variable `x`
--> fail_wrapper.rs:7:5
|
7 | Wrapper { value: &x }
| ^^^^^^^^^^^^^^^^^--^^
| | |
| | `x` is borrowed here
| returns a value referencing data owned by the current function
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0515`.
The underline spans the whole struct expression, with "x is borrowed here" marking the field initializer: the borrow is taken while building the returned value, which is exactly what makes the returned value invalid. The fix restructures who creates the referent. The caller creates the number and passes a reference in; the function only assembles the wrapper around a borrow it was given, and the wrapper's lifetime is the input's lifetime rather than a promise about a local:
struct Wrapper<'a> {
value: &'a i32,
}
fn make_wrapper<'a>(input: &'a i32) -> Wrapper<'a> {
Wrapper { value: input }
}
fn main() {
let x = 7;
let w = make_wrapper(&x);
println!("{}", w.value);
}
$ rustc --edition 2021 fix_wrapper.rs -o fix_wrapper
$ ./fix_wrapper
7
The printed 7 is read through the field after the call, from a value owned by main that outlives the wrapper. The pattern generalizes past this small struct: a function may freely return containers of references, as long as every referent is owned outside the function — by the caller, or by something the caller passed in. What it may not do is manufacture a referent and export a view of it.
The fixes in reach order
- Return the owned value when the function creates what the caller needs: a
String, aVec, a number. Ownership moves out, nothing is dropped at the return, and no lifetime reasoning remains. - Return a reference to caller-owned input when the function only selects from or views data the caller already has: state the relationship in the signature (
fn first_two<'a>(v: &'a [i32]) -> &'a [i32]), or let the elision rules supply it where they apply. - Restructure so the caller creates the value and passes a reference in when the returned thing is a container of references — a struct, a tuple, an iterator: the function assembles views of caller-owned data instead of manufacturing referents.
- Return an owned container when the data must be created inside the function and handed over in bulk: collecting an iterator into a
Vecthe caller owns beats returning the iterator over a local collection. - Keep a
'staticreturn only for referents that genuinely live for the whole program, such as string literals — never as a promise made on behalf of a local.
Traps
- Adding
'static, or any lifetime, to the signature does not extend a local's life. All four failing programs above promise'staticand all four fail; annotations describe relationships, they do not move drops. - The plain form of this mistake often never reaches E0515: a signature like
fn make_number() -> &i32, with no lifetime at all, is rejected earlier as E0106, missing lifetime specifier, because there is no input for the returned reference to be borrowed from. E0515 appears once the signature names a lifetime the body cannot honor. - Returning a reference to a parameter is not this error. A parameter's referent is owned by the caller and lives past the return, which is why the third and fourth families' fixes compile: the defect was never "returning a reference", it was returning a reference to a value the function itself owned.
- A string literal is the honest
'static: the Book notes that all string literals have the'staticlifetime, because their text is stored in the program's binary. A function returning the literal"hello"as&'static strcompiles; a function returning a slice of aStringit built does not, and the difference is who owns the storage. - Wrapping the reference does not hide it. A struct field, a slice, and an iterator over a local all carry the borrow across the return, and the diagnostic follows the borrow into each of them — the "value referencing" wording is the compiler naming the wrapper, not a lesser error.
- Cloning at the return is the owned fix wearing a disguise, and sometimes the right one: returning a clone of a local the function must also keep is a deliberate owned return. What does not work is returning the reference and hoping the clone question goes away.
Decision summary
- The function builds a
String, a collection, or a computed value and the caller needs it: return it owned. - The diagnostic says "reference to local variable": the return expression is
&localitself — replace it with the value, or with a reference to an input. - The diagnostic says "value referencing local variable": the return is a slice, a struct, or another view of a local — move the referent's creation to the caller, or return an owned container instead of the view.
- The function only selects from data the caller has: take the data by reference and return a reference tied to it by a lifetime — written out, or elided where the elision rules apply.
- The signature promises
'staticover a local: the promise is the defect — no annotation makes a local outlive its function. - The report is E0106 rather than E0515: the signature names no lifetime and borrows from nothing; the repair is the same owned return, reached one diagnostic earlier.
Checklist
- The returned thing classified before editing: a plain reference to a local, or a value — a slice, a struct, an iterator — that references one.
- The fix changed what crosses the return: an owned value out, or a reference whose referent is caller-owned and stated with a lifetime.
- No lifetime annotation treated as if it lengthens a local's life;
'staticappears only where the referent genuinely lives for the whole program. - Where a reference is returned, its referent identified by name and owned by the caller, not by the returning function.
- The fixed program run, and its output checked against what the failing program was trying to compute.
Related guides on this site
- Fix Rust E0507 "cannot move out of ..." — Vec Index, HashMap Index, a Shared Reference, a Struct Field, and a Mutable Reference
- Fix Rust E0596 "cannot borrow as mutable" — a Vec Without mut, a Function Taking &Vec, a &self Method Pushing to a Field, and a Shared Reference in a Binding
- E0425 Cannot Find Value Fix
- Fix Rust E0597 "`x` does not live long enough" — a Block Scope, a Stored Reference, a Struct Field, and a Closure Capture
Sources
- Rust, Error codes index: E0515 — the definition of the error: a reference to a local variable was returned; locals, parameters and temporaries are dropped before the end of the function body; a returned reference, or a struct containing a reference, to such a value would immediately be invalid; and the owned-value alternative.
- The Rust Programming Language, References and Borrowing — references must always be valid, the compiler guarantee that references are never dangling, the dangling-reference example of a function returning a reference to its own local
String, and the solution of returning the ownedStringdirectly. - The Rust Programming Language, Validating References with Lifetimes — lifetime annotations describe relationships without affecting how long values live, the lifetime elision rules that assign a single input lifetime to the output, and the
'staticlifetime of string literals.
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.