Skip to Content
E0515: Returning a Reference to a Local

error[E0515]: cannot return reference to local variable

A function tried to return a reference to a value it created itself. That value is dropped when the function returns, so the reference would dangle immediately.

Quick fix: Return the owned value (String instead of &str, Vec<T> instead of &[T]).

Code that triggers E0515

src/main.rs
fn make_greeting(name: &str) -> &str { let greeting = format!("Hello, {name}!"); &greeting } fn main() { println!("{}", make_greeting("Ferris")); }

What the compiler says

error[E0515]: cannot return reference to local variable `greeting` --> src/main.rs:3:5 | 3 | &greeting | ^^^^^^^^^ 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`.

Why Rust raises E0515

greeting is a local String owned by make_greeting. It’s dropped when the function returns, so a reference to it would point at freed memory the moment the caller received it.

This often comes from a signature that returns &str out of habit. A function can only return a reference if it borrows from one of its inputs, or from something 'static such as a string literal. The same error appears with cannot return value referencing local variable when you return something that borrows a local, like an iterator over a local Vec.

How to fix E0515

1. Return an owned value

Return the String itself. Ownership moves to the caller, so there’s nothing left to dangle. This is the right fix in almost every case.

src/main.rs
fn make_greeting(name: &str) -> String { format!("Hello, {name}!") } fn main() { println!("{}", make_greeting("Ferris")); }

2. Return a reference into an input

If the result really is part of an argument, returning a reference is fine, because the data outlives the call. Here the returned &str points into the caller’s sentence.

src/main.rs
fn first_word(text: &str) -> &str { text.split(' ').next().unwrap_or("") } fn main() { let sentence = String::from("Hello Ferris"); println!("{}", first_word(&sentence)); }

Learn the concept behind it

The References and Borrowing lesson explains the rules behind E0515 with diagrams and more examples. For the official reference, run rustc --explain E0515 or read the E0515 entry in the Rust error index .

Hit a different error? Paste it into the Rust error lookup to find its fix.

Last updated on