Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Rust E0106: missing lifetime specifier

E0106 appears when a returned borrow has no input to borrow from. Name the lifetime in functions, structs and impls, or return owned data.

~5 min readRust
#rust#lifetimes#borrow-checker#e0106
Bold white headline reading E0106 with a Rust reference crate floating over an amber unlabelled value cube and a cyan input rail.

Introduction & Quick Summary

A small refactor stops the build at the first function:

code
error[E0106]: missing lifetime specifier --> src/lib.rs:4:31 | 4 | fn pick(a: &str, b: &str) -> &str { | ---- ---- ^ 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

Quick answer: the return type borrows, but with two inputs the compiler cannot tell which one it borrows from. Name both with one lifetime.

rust
fn pick<'a>(a: &'a str, b: &'a str) -> &'a str { if a.len() >= b.len() { a } else { b } }

E0106 is not about memory safety in the abstract; it is about a missing piece of information. When a signature has exactly one input reference, Rust assigns that lifetime to every elided output reference, which is why fn first(s: &str) -> &str compiles without an annotation. With two or more inputs, the rule has no answer and the compiler asks you to choose rather than guess.

The same error appears in struct definitions, where the rule is simpler: any field holding a reference needs a lifetime parameter on the type.

rust
struct Name<'a> { value: &'a str } // without <'a>, E0106 on the field

Three situations produce it in practice: a function returning a reference derived from one of several inputs, a struct or enum storing borrows, and a trait object whose borrowed data has no stated lifetime.

Core Mechanics, Signatures & Reproducible Setup

Reproduce all three shapes in a scratch crate:

bash
cargo new --lib lifetimes && cd lifetimes cat > src/lib.rs <<'RS' pub fn pick(a: &str, b: &str) -> &str { a } // E0106 pub struct Holder { name: &str } // E0106 on the field pub fn make() -> &str { "static is fine" } // ok, 'static RS cargo build

The elision rules that decide when an annotation is required:

RuleStatementEffect
1each elided input lifetime becomes its own parameterfn f(a: &str, b: &str) has two distinct lifetimes
2one input lifetime is assigned to every elided outputfn f(a: &str) -> &str ties the output to a
3&self or &mut self is assigned to elided outputsmethods usually need no annotation
—zero input lifetimes, output elidedE0106, nothing to borrow from
—two or more inputs, output elidedE0106, ambiguous
SignatureCompilesWhy
fn f(s: &str) -> &stryesone input, rule 2
fn f(a: &str, b: &str) -> &strnotwo inputs, no rule
fn f(a: &str, b: &str) -> &'static stryesoutput does not borrow
fn f(&self) -> &stryesrule 3
fn f(&self, other: &str) -> &stryesrule 3 wins
fn f() -> &strnonothing to borrow from

Key Comparison Table

GoalSignatureCostBest for
Borrow one inputfn f<'a>(x: &'a str) -> &'a strnonepure transforms
Borrow from the longer-lived inputfn f<'a, 'b: 'a>(x: &'a str, y: &'b str) -> &'a strnonemerges with a dominant source
Return owned datafn f(x: &str) -> Stringallocationvalues that outlive the input
Borrow or ownfn f(x: &str) -> Cow<'_, str>allocation only when modifiednormalisation, escaping
Store borrowed textstruct S<'a> { v: &'a str }noneviews into a buffer
Store owned textstruct S { v: String }one allocationlong-lived models
Erase the lifetimeBox<dyn Trait + 'a>indirectionheterogeneous collections

Errors in the same family, and what each really means:

ErrorMeaningTypical fix
E0106 missing lifetime specifierno lifetime could be inferredannotate the signature
E0515 cannot return value referencing local variablethe data dies at the end of the functionreturn owned data
E0597 borrowed value does not live long enoughthe owner is dropped too earlyreorder or own the value
E0495 cannot infer an appropriate lifetimeconstraints conflictrestructure or relax the bound
E0621 explicit lifetime required in the type of xparameter must be borrowedchange the parameter type

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Two inputs, one output: say which one you return

rust
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str { if a.len() >= b.len() { a } else { b } }

Writing <'a> on both parameters tells the compiler the result may borrow from either, so it lives only as long as the shorter of the two. That is correct and conservative. When one input clearly dominates, express it:

rust
fn join_prefix<'a, 'b: 'a>(prefix: &'a str, name: &'b str) -> &'a str { prefix // returns the longer-lived one, and the bound says so }

An over-constrained signature compiles and then refuses real call sites. Start loose and tighten only when a borrow checker error demands it.

2. Structs that hold borrows

rust
pub struct Parser<'input> { source: &'input str, pos: usize, } impl<'input> Parser<'input> { pub fn new(source: &'input str) -> Self { Self { source, pos: 0 } } pub fn rest(&self) -> &'input str { &self.source[self.pos..] } }

Two details matter. The impl block repeats the lifetime, and rest returns &'input str rather than &str: with rule 3 an elided output would borrow from self, which is shorter than the input. A parser that wraps a temporary String cannot store a reference to it — the owner must outlive the struct, which is why parsers are often generic over &'input str and take ownership of nothing.

3. Methods, &self and the third rule

rust
impl<'a> Parser<'a> { pub fn peek(&self) -> &str { &self.source[self.pos..self.pos + 1] } // borrows self pub fn source(&self) -> &'a str { self.source } // borrows the input }

Both compile, and they differ in what the caller may do afterwards. A peek() result keeps the parser mutably borrowed for as long as it is used, so let c = p.peek(); p.advance(); fails with a borrow error. Returning the input lifetime instead lets the caller keep the slice while the parser keeps working — the design decision behind many parsers' &'input str returns.

4. Returning a reference to local data is E0515, not E0106

rust
fn label() -> &str { let s = String::from("temporary"); &s // E0515: cannot return value referencing local variable }

The compiler already knows the lifetime here; the data simply dies. The fix is ownership or a caller-provided buffer:

rust
fn label() -> String { String::from("temporary") } fn write_label(out: &mut String) { out.push_str("temporary"); } fn label_cow(name: &str) -> Cow<'_, str> { if name.is_empty() { Cow::Borrowed("anonymous") } else { Cow::Borrowed(name) } }

Knowing which of the two errors you have saves time: E0106 needs annotation, E0515 needs a different return type.

5. Trait objects, closures and 'static bounds

rust
trait Renderer { fn render(&self) -> String; } struct App<'a> { renderer: Box<dyn Renderer + 'a> } fn spawn_render(job: impl Fn() -> String + 'static) { /* … */ }

A Box<dyn Trait> defaults to 'static when no lifetime is written, so storing a renderer that borrows local data requires + 'a. A closure that captures a reference and is sent to another thread needs 'static because the thread outlives the call. The compiler message for these cases is usually borrowed value does not live long enough plus a suggestion to add move, which changes ownership rather than the lifetime.

6. Async functions and borrowed arguments

rust
async fn read_chunk<'a>(src: &'a str, n: usize) -> &'a str { &src[..n.min(src.len())] }

An async fn desugars into a future that may hold its arguments, so elision rules apply to the returned future as well. A future borrowing an argument cannot be spawned on a runtime that requires 'static; tokio::spawn rejects it with a lifetime error at the spawn call, not at the definition. Convert to owned data inside the async block when the future must outlive the call site. When two versions of a signature misbehave, comparing them with the text diff tool shows whether a lifetime was dropped during a refactor, and the regex tester helps find every fn returning &str in a large crate.

Common Compilation/Runtime Mistakes & Version Gotchas

Adding 'static to silence the error. It compiles only when the data really is static; otherwise it produces a longer cascade of errors at every call site.

Writing <'a> on the return type only. Lifetimes must be introduced in the generic parameter list and used on inputs, or the compiler reports an unused lifetime.

Assuming lifetimes affect runtime. They are erased entirely; an annotation cannot leak memory or change performance.

Returning &str from a function that builds a String. No combination of lifetimes makes that legal. Return String or Cow.

Forgetting the lifetime on the impl block. impl Parser without <'input> fails with E0107 (missing generics), a different code that appears right after fixing E0106.

Version notes. Rust 2018 made dyn Trait mandatory and requires + '_ in more positions than 2015 taught. Rust 2021 allows impl Trait for Struct<'_> in more places. The async fn in traits feature, stable since Rust 1.75, changed how lifetime bounds on trait methods are written; a trait with async fn and a borrowed receiver needs + Send bounds that older guides do not mention.

Reference material: E0106 and Validating references with lifetimes.

Official references

primary documentation

The Rust documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Rust guides

More in Rust

All Rust guides

The guides filed next to this one in Rust, in library order.