Email me

Rust errors / Everything else

Rust compiler error · checked with rustc 1.99.0

Rust error E0515: cannot return reference to local variable

What it meansThe function returns a reference to something it created itself. That value is dropped when the function returns, so the reference would point at freed memory. Return the owned value instead.

What rustc prints

error[E0515]: cannot return reference to local variable `x`
 --> main.rs:3:5
  |
3 |     &x
  |     ^^ returns a reference to data owned by the current function

Real output of rustc 1.99.0 compiling the official example below (2021 edition). Your names and line numbers will differ; the first line is the part to match.

Why it happens

  • Returning &s or s.as_str() where s is a String built inside the function.
  • Returning a slice of a Vec created in the function.
  • Returning an iterator that borrows a local collection.

How to fix it

1. Return the owned value

Hand ownership to the caller.

fn name() -> String {
    let s = format!("{}-{}", "a", "b");
    s  // not &s
}

2. Borrow from an input instead

If the data comes from a parameter, return a reference tied to it.

fn first_word(s: &str) -> &str {
    s.split(' ').next().unwrap_or("")
}

3. Return Cow when it is sometimes borrowed

use std::borrow::Cow;
fn clean(s: &str) -> Cow<'_, str> {
    if s.contains('\t') { Cow::Owned(s.replace('\t', " ")) } else { Cow::Borrowed(s) }
}

Other wordings of this error

cannot return reference to local variable, returns a reference to data owned by the current function, cannot return value referencing local variable, cannot return value referencing temporary value

E0515Everything else
Activein rustc 1.99.0
8related errors linked below

The compiler team's explanation

A reference to a local variable was returned.

Erroneous code example:

fn get_dangling_reference() -> &'static i32 {
    let x = 0;
    &x
}
use std::slice::Iter;
fn get_dangling_iterator<'a>() -> Iter<'a, i32> {
    let v = vec![1, 2, 3];
    v.iter()
}

Local variables, function parameters and temporaries are all dropped before the end of the function body. A returned reference (or struct containing a reference) to such a dropped value would immediately be invalid. Therefore it is not allowed to return such a reference.

Consider returning a value that takes ownership of local data instead of referencing it:

use std::vec::IntoIter;

fn get_integer() -> i32 {
    let x = 0;
    x
}

fn get_owned_iterator() -> IntoIter<i32> {
    let v = vec![1, 2, 3];
    v.into_iter()
}

From rustc --explain E0515 (1.99.0), part of the Rust project, MIT or Apache-2.0. Official page.

Related errors

All 518 Rust error codes · Rust crate data · Glossary

Up next

Often hit nextE0061: this function takes N arguments but M were suppliedA related error from the same family.Read it next →

Did this answer your question?

Get the receipts by email.

What my AI agents tried this week, with the real numbers: what worked, what flopped, what made money. One email when there is something worth reading.

No spam, never sold. Every email has a one-click unsubscribe.

Popular in the shop

All 124 tools →

Browse: Bundles and kitsHome, family and schoolMoney and businessAI toolsSports and fitnessMaking and hobbiesFood and drinkIndie dev and launchTrading and quant

Free: Landing page teardown iPhone app cost calculator LLM API cost calculator Paid online: $49 Launch Check App builds Articles FAQ