Rust
E0621 Explicit Lifetime Required Fix
A return type can only promise what the signature names. When a function declares that its result is borrowed for the lifetime of one parameter and the body hands back data borrowed from another parameter that was never tied to that lifetime, the compiler has no way to know the returned data lives long enough - and E0621 names the parameter whose type is missing the lifetime. This guide separates the eleven shapes that produce it and matches each one to its repair: tie the parameter the returned data comes from to the same lifetime, narrow the body to the data the signature already promises, or return an owned value and drop the promise entirely.
Written November 25, 2026 · Tested with Rust 1.99.1 · 28 min read
- The rule underneath: a signature is a promise about data-flow
- How to read the diagnostic
- The first failure: choosing between two references
- The second failure: returning the second parameter directly
Written November 25, 2026
Tested with Rust 1.99.1
What this guide is
Error E0621 is a mismatch between a function signature and its body over lifetimes. The error codes index describes it as a mismatch between the lifetimes appearing in the function signature - the parameter types and the return type - and the data-flow found in the function body. Its example is a function returning &'a i32 from two integer parameters, only one of which is typed &'a i32: the body may return the second parameter's data, but the signature has promised that everything returned lives for 'a, and nothing in the second parameter's type says its data does. The diagnostic names that parameter directly - "explicit lifetime required in the type of y" - and its help writes the repair into the signature.
The forms in this guide each reproduce E0621 with a small, complete program, and in each one the returned data flows from a different place: the other of two parameters chosen conditionally, the second parameter returned outright, a string slice, an element of a slice, a field of a struct parameter, an argument of a method whose result is tied to self, one arm of a match, the result of a nested call, an element of a Vec, a mutable reference, and a subslice of a string. The repairs are fewer than the shapes. Either the parameter the data comes from is given the named lifetime, so the signature tells the truth about the body, or the body is changed so it only returns what the signature already promises, or the function stops returning a reference at all.
Several neighboring results are not E0621 and are worked only in their own sections below. A return type with a borrowed value and no input to borrow it from - and the same gap with two inputs and no named lifetime anywhere - is E0106, missing lifetime specifier, because there is no named lifetime for a parameter to be tied to. A local that is borrowed after its scope ends is E0597. Two parameters carrying two different named lifetimes, with the body returning the wrong one, fail with a lifetime error that carries no error code at all.
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 signature is a promise about data-flow
A lifetime parameter in a signature is a claim the caller can rely on: a result typed &'a i32 will remain valid for as long as 'a lasts. The error codes index states the consequence from the other side: in its example the 'a annotation indicates the function is returning data only from x, so a body that can also return data from y contradicts the annotation. The compiler checks the body against the signature, finds a path where data borrowed from an untied parameter reaches the return, and reports the parameter - not the return statement - because the parameter's type is where the missing fact belongs.
The default that makes this error feel surprising is elision. The lifetime elision rules in the Reference assign lifetimes automatically in common shapes: each elided lifetime in input position becomes its own lifetime parameter, a single input lifetime is assigned to every elided output lifetime, and for a method the lifetime of &self or &mut self is assigned to the outputs. Elision is why a one-input function returning a reference needs no annotations at all, as the neighbors below show. But elision never ties two different inputs together, and the moment a signature names one lifetime explicitly - &'a on one parameter and on the return - every other input the body uses is outside that promise until its type names the same lifetime.
That is also why the fix is almost always in the signature rather than the body. Adding 'a to the second parameter does not change what the function does; it changes what callers must guarantee - both arguments must now live for 'a - which is exactly the fact the body already depended on. Where that guarantee is more than callers should have to give, the honest repairs are the other two: return only the tied parameter's data, or return an owned value and let the promise go.
How to read the diagnostic
Every failure in the eleven families prints the same shape of output. The first family's, in full:
$ rustc --edition 2021 fail_two_refs.rs -o fail_two_refs
error[E0621]: explicit lifetime required in the type of `y`
--> fail_two_refs.rs:2:27
|
2 | if x > y { x } else { y }
| ^ lifetime `'a` required
|
help: add explicit lifetime `'a` to the type of `y`
|
1 | fn foo<'a>(x: &'a i32, y: &'a i32) -> &'a i32 {
| ++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0621`.
Read it in order. The header names the parameter whose type is missing the lifetime - that parameter is the diagnosis, and the families below are organized by where the returned data comes from, which is what decides that parameter. The span points at the expression that returns the untied data and labels it "lifetime 'a required". The help then rewrites the signature line with the lifetime added to that parameter's type, which for most programs is the complete fix, ready to copy. When the help's version of the signature is not the contract the function should offer, the alternatives section below gives the two body-side repairs.
That shape is also the fastest way to separate E0621 from its neighbors before touching code. If the header says "explicit lifetime required in the type of" a parameter, a named lifetime exists and one parameter is outside it - this guide applies. If it says "missing lifetime specifier" (E0106), no lifetime has been named yet and the signature needs one before any parameter can be tied to it. If it says a value "does not live long enough" (E0597), the signature is not the problem at all - the data itself ends too soon.
The first failure: choosing between two references
The example from the error codes index - a function that returns whichever of two integer references is larger, with only the first tied to the return lifetime:
fn foo<'a>(x: &'a i32, y: &i32) -> &'a i32 {
if x > y { x } else { y }
}
fn main() {
let a = 1;
let b = 2;
println!("{}", foo(&a, &b));
}
$ rustc --edition 2021 fail_two_refs.rs -o fail_two_refs
error[E0621]: explicit lifetime required in the type of `y`
--> fail_two_refs.rs:2:27
|
2 | if x > y { x } else { y }
| ^ lifetime `'a` required
|
help: add explicit lifetime `'a` to the type of `y`
|
1 | fn foo<'a>(x: &'a i32, y: &'a i32) -> &'a i32 {
| ++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0621`.
The body can return y, so the promise -> &'a i32 is only honored if y's data also lives for 'a. The fix names 'a on y, exactly as the diagnostic's help proposes:
fn foo<'a>(x: &'a i32, y: &'a i32) -> &'a i32 {
if x > y { x } else { y }
}
fn main() {
let a = 1;
let b = 2;
println!("{}", foo(&a, &b));
}
$ rustc --edition 2021 fix_two_refs.rs -o fix_two_refs
$ ./fix_two_refs
2
The output is 2, the larger value, now returnable from either parameter. Nothing about the body's logic changed - the signature finally states the requirement the comparison already imposed, that both arguments outlive the result.
The second failure: returning the second parameter directly
A program whose body returns the untied parameter outright, ignoring the tied one:
fn pick<'a>(x: &'a i32, y: &i32) -> &'a i32 {
let _ = x;
y
}
fn main() {
let a = 1;
let b = 2;
println!("{}", pick(&a, &b));
}
$ rustc --edition 2021 fail_return_second.rs -o fail_return_second
error[E0621]: explicit lifetime required in the type of `y`
--> fail_return_second.rs:3:5
|
3 | y
| ^ lifetime `'a` required
|
help: add explicit lifetime `'a` to the type of `y`
|
1 | fn pick<'a>(x: &'a i32, y: &'a i32) -> &'a i32 {
| ++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0621`.
There is no conditional to hide behind here: every call returns y's data under a signature that promises x's lifetime. The fix ties y to 'a:
fn pick<'a>(x: &'a i32, y: &'a i32) -> &'a i32 {
let _ = x;
y
}
fn main() {
let a = 1;
let b = 2;
println!("{}", pick(&a, &b));
}
$ rustc --edition 2021 fix_return_second.rs -o fix_return_second
$ ./fix_return_second
2
The output is 2. When the returned parameter is the only one the body uses, tying it is the whole repair - the tied-but-unused parameter stays in the signature because the function's interface, not this guide, decides whether it belongs there.
The third failure: choosing between two string slices
The same choice as the first family, over &str values picked by length:
fn pick<'a>(a: &'a str, b: &str) -> &'a str {
if a.len() > b.len() { a } else { b }
}
fn main() {
println!("{}", pick("longer", "hi"));
}
$ rustc --edition 2021 fail_str_pick.rs -o fail_str_pick
error[E0621]: explicit lifetime required in the type of `b`
--> fail_str_pick.rs:2:39
|
2 | if a.len() > b.len() { a } else { b }
| ^ lifetime `'a` required
|
help: add explicit lifetime `'a` to the type of `b`
|
1 | fn pick<'a>(a: &'a str, b: &'a str) -> &'a str {
| ++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0621`.
String slices are borrowed data like any other reference, so the untied slice b is named in the header. The fix ties b to 'a:
fn pick<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() > b.len() { a } else { b }
}
fn main() {
println!("{}", pick("longer", "hi"));
}
$ rustc --edition 2021 fix_str_pick.rs -o fix_str_pick
$ ./fix_str_pick
longer
The output is longer. The length comparison reads both slices but returns only one of them, and reading is not what the lifetime governs - returning is. Both slices must still be tied, because which one is returned is only known at run time.
The fourth failure: an element of a slice
A program that returns a reference into a slice parameter, while the named lifetime sits on an unrelated parameter:
fn first<'a>(keep: &'a i32, vals: &[i32]) -> &'a i32 {
let _ = keep;
&vals[0]
}
fn main() {
let k = 9;
let v = [1, 2, 3];
println!("{}", first(&k, &v));
}
$ rustc --edition 2021 fail_slice_first.rs -o fail_slice_first
error[E0621]: explicit lifetime required in the type of `vals`
--> fail_slice_first.rs:3:5
|
3 | &vals[0]
| ^^^^^^^^ lifetime `'a` required
|
help: add explicit lifetime `'a` to the type of `vals`
|
1 | fn first<'a>(keep: &'a i32, vals: &'a [i32]) -> &'a i32 {
| ++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0621`.
The returned reference points inside vals, so vals is the parameter the header names - the element's lifetime is the slice's lifetime, not the element type's. The fix ties the slice to 'a:
fn first<'a>(keep: &'a i32, vals: &'a [i32]) -> &'a i32 {
let _ = keep;
&vals[0]
}
fn main() {
let k = 9;
let v = [1, 2, 3];
println!("{}", first(&k, &v));
}
$ rustc --edition 2021 fix_slice_first.rs -o fix_slice_first
$ ./fix_slice_first
1
The output is 1, the first element. A reference to an element can never outlive the container it indexes into, which is why the container's parameter is always the one E0621 names in this shape.
The fifth failure: a field of a struct parameter
A program that returns a reference to a field of its second struct parameter:
struct Rec {
v: i32,
}
fn get<'a>(a: &'a Rec, b: &Rec) -> &'a i32 {
let _ = a;
&b.v
}
fn main() {
let a = Rec { v: 1 };
let b = Rec { v: 2 };
println!("{}", get(&a, &b));
}
$ rustc --edition 2021 fail_struct_field.rs -o fail_struct_field
error[E0621]: explicit lifetime required in the type of `b`
--> fail_struct_field.rs:6:5
|
6 | &b.v
| ^^^^ lifetime `'a` required
|
help: add explicit lifetime `'a` to the type of `b`
|
4 | fn get<'a>(a: &'a Rec, b: &'a Rec) -> &'a i32 {
| ++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0621`.
The field reference is borrowed from b as a whole - &b.v lives exactly as long as the borrow of b does. The fix ties b to 'a:
struct Rec {
v: i32,
}
fn get<'a>(a: &'a Rec, b: &'a Rec) -> &'a i32 {
let _ = a;
&b.v
}
fn main() {
let a = Rec { v: 1 };
let b = Rec { v: 2 };
println!("{}", get(&a, &b));
}
$ rustc --edition 2021 fix_struct_field.rs -o fix_struct_field
$ ./fix_struct_field
2
The output is 2, the second record's field. Field access does not create a new lifetime or detach the field from its owner; a reference to a part is a borrow of the whole for lifetime purposes.
The sixth failure: a method returning an argument
A method whose return type is tied to the lifetime of &self, but whose body returns a separate string argument:
struct Holder {
name: String,
}
impl Holder {
fn pick<'a>(&'a self, other: &str) -> &'a str {
other
}
}
fn main() {
let h = Holder { name: String::from("n") };
println!("{}", h.pick("other"));
}
$ rustc --edition 2021 fail_method.rs -o fail_method
error[E0621]: explicit lifetime required in the type of `other`
--> fail_method.rs:6:9
|
6 | other
| ^^^^^ lifetime `'a` required
|
help: add explicit lifetime `'a` to the type of `other`
|
5 | fn pick<'a>(&'a self, other: &'a str) -> &'a str {
| ++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0621`.
Methods feel different because elision normally ties their outputs to self - and here that tie was made explicit with &'a self, which puts the argument other outside the promise in exactly the free-function way. The fix ties other to the same 'a:
struct Holder {
name: String,
}
impl Holder {
fn pick<'a>(&'a self, other: &'a str) -> &'a str {
let _ = &self.name;
other
}
}
fn main() {
let h = Holder { name: String::from("n") };
println!("{}", h.pick("other"));
}
$ rustc --edition 2021 fix_method.rs -o fix_method
$ ./fix_method
other
The output is other. The method receiver is a parameter for lifetime purposes; an explicit lifetime on self creates the same contract, and the same gap, as one on any other parameter.
The seventh failure: one arm of a match
A program that selects between the tied and untied parameters with a match on a flag:
fn pick<'a>(x: &'a i32, y: &i32, flag: bool) -> &'a i32 {
match flag {
true => x,
false => y,
}
}
fn main() {
let a = 1;
let b = 2;
println!("{}", pick(&a, &b, false));
}
$ rustc --edition 2021 fail_match.rs -o fail_match
error[E0621]: explicit lifetime required in the type of `y`
--> fail_match.rs:2:5
|
2 | / match flag {
3 | | true => x,
4 | | false => y,
5 | | }
| |_____^ lifetime `'a` required
|
help: add explicit lifetime `'a` to the type of `y`
|
1 | fn pick<'a>(x: &'a i32, y: &'a i32, flag: bool) -> &'a i32 {
| ++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0621`.
A match arm is a return path like any other, and the false arm returns y. The fix ties y to 'a:
fn pick<'a>(x: &'a i32, y: &'a i32, flag: bool) -> &'a i32 {
match flag {
true => x,
false => y,
}
}
fn main() {
let a = 1;
let b = 2;
println!("{}", pick(&a, &b, false));
}
$ rustc --edition 2021 fix_match.rs -o fix_match
$ ./fix_match
2
The output is 2, from the false arm - the very path the signature could not cover. Conditional expressions, if and match alike, are checked arm by arm, and one untied arm is enough for the error.
The eighth failure: passing the untied parameter to another function
A program that passes its untied parameter into a helper whose own signature is fully tied:
fn id<'a>(v: &'a i32) -> &'a i32 {
v
}
fn outer<'a>(x: &'a i32, y: &i32) -> &'a i32 {
let _ = x;
id(y)
}
fn main() {
let a = 1;
let b = 2;
println!("{}", outer(&a, &b));
}
$ rustc --edition 2021 fail_nested_call.rs -o fail_nested_call
error[E0621]: explicit lifetime required in the type of `y`
--> fail_nested_call.rs:6:5
|
6 | id(y)
| ^^^^^ lifetime `'a` required
|
help: add explicit lifetime `'a` to the type of `y`
|
4 | fn outer<'a>(x: &'a i32, y: &'a i32) -> &'a i32 {
| ++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0621`.
The error still lands in outer, on its y: id requires an &'a i32, and handing it y is the moment y's data is committed to the 'a promise. The fix ties y in outer's signature - id needs no change:
fn id<'a>(v: &'a i32) -> &'a i32 {
v
}
fn outer<'a>(x: &'a i32, y: &'a i32) -> &'a i32 {
let _ = x;
id(y)
}
fn main() {
let a = 1;
let b = 2;
println!("{}", outer(&a, &b));
}
$ rustc --edition 2021 fix_nested_call.rs -o fix_nested_call
$ ./fix_nested_call
2
The output is 2. E0621 is reported where the promise is made, not where it is kept: the helper's signature was already honest, and the caller's was not.
The ninth failure: an element of a Vec
A program that returns a reference to an element of a Vec parameter:
fn pick<'a>(x: &'a String, items: &Vec<String>) -> &'a String {
let _ = x;
&items[0]
}
fn main() {
let x = String::from("x");
let v = vec![String::from("a")];
println!("{}", pick(&x, &v));
}
$ rustc --edition 2021 fail_vec_ref.rs -o fail_vec_ref
error[E0621]: explicit lifetime required in the type of `items`
--> fail_vec_ref.rs:3:5
|
3 | &items[0]
| ^^^^^^^^^ lifetime `'a` required
|
help: add explicit lifetime `'a` to the type of `items`
|
1 | fn pick<'a>(x: &'a String, items: &'a Vec<String>) -> &'a String {
| ++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0621`.
As with the slice family, the element reference borrows the container, so items is the named parameter. The fix ties items to 'a:
fn pick<'a>(x: &'a String, items: &'a Vec<String>) -> &'a String {
let _ = x;
&items[0]
}
fn main() {
let x = String::from("x");
let v = vec![String::from("a")];
println!("{}", pick(&x, &v));
}
$ rustc --edition 2021 fix_vec_ref.rs -o fix_vec_ref
$ ./fix_vec_ref
a
The output is a, the element's text. Indexing into any container - slice, array, or Vec - produces a borrow of the container, and the container's parameter carries the lifetime.
The tenth failure: a mutable reference
A program that returns its second &mut parameter under the first parameter's lifetime:
fn pick<'a>(x: &'a mut i32, y: &mut i32) -> &'a mut i32 {
let _ = x;
y
}
fn main() {
let mut a = 1;
let mut b = 2;
println!("{}", pick(&mut a, &mut b));
}
$ rustc --edition 2021 fail_mut_ref.rs -o fail_mut_ref
error[E0621]: explicit lifetime required in the type of `y`
--> fail_mut_ref.rs:3:5
|
3 | y
| ^ lifetime `'a` required
|
help: add explicit lifetime `'a` to the type of `y`
|
1 | fn pick<'a>(x: &'a mut i32, y: &'a mut i32) -> &'a mut i32 {
| ++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0621`.
Mutability changes what can be done with the reference, not how long it lives, so the same gap is reported in the same words. The fix ties the second parameter to 'a:
fn pick<'a>(x: &'a mut i32, y: &'a mut i32) -> &'a mut i32 {
let _ = x;
y
}
fn main() {
let mut a = 1;
let mut b = 2;
println!("{}", pick(&mut a, &mut b));
}
$ rustc --edition 2021 fix_mut_ref.rs -o fix_mut_ref
$ ./fix_mut_ref
2
The output is 2. A mutable borrow is still a borrow; its lifetime must be named wherever an immutable one's would be.
The eleventh failure: a subslice of a string
A program that returns a subslice of its second string parameter:
fn tail<'a>(head: &'a str, s: &str) -> &'a str {
let _ = head;
&s[1..]
}
fn main() {
println!("{}", tail("keep", "hello"));
}
$ rustc --edition 2021 fail_str_slice.rs -o fail_str_slice
error[E0621]: explicit lifetime required in the type of `s`
--> fail_str_slice.rs:3:5
|
3 | &s[1..]
| ^^^^^^^ lifetime `'a` required
|
help: add explicit lifetime `'a` to the type of `s`
|
1 | fn tail<'a>(head: &'a str, s: &'a str) -> &'a str {
| ++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0621`.
Slicing borrows: &s[1..] is data inside s, with s's lifetime. The fix ties s to 'a:
fn tail<'a>(head: &'a str, s: &'a str) -> &'a str {
let _ = head;
&s[1..]
}
fn main() {
println!("{}", tail("keep", "hello"));
}
$ rustc --edition 2021 fix_str_slice.rs -o fix_str_slice
$ ./fix_str_slice
ello
The output is ello. A subslice has no storage of its own - it is a pointer and a length into the original string - so its lifetime is the original parameter's, and that parameter is the one that must be named.
Seven more shapes that fail the same way
The same header, naming whichever parameter the returned data flows from, for seven more programs. Each fails with exactly one E0621 and no other error, and each is repaired by naming 'a on that parameter:
An Option parameter unwrapped - the reference inside the option carries the option parameter's borrow:
fn pick<'a>(x: &'a i32, y: Option<&i32>) -> &'a i32 {
if let Some(v) = y {
v
} else {
x
}
}
fn main() {
let a = 1;
let b = 2;
println!("{}", pick(&a, Some(&b)));
}
A generic parameter - the same gap over &T:
fn pick<'a, T>(x: &'a T, y: &T) -> &'a T {
if true { x } else { y }
}
fn main() {
let a = 1;
let b = 2;
println!("{}", pick(&a, &b));
}
A field of a tuple parameter:
fn pick<'a>(x: &'a i32, pair: &(i32, i32)) -> &'a i32 {
let _ = x;
&pair.1
}
fn main() {
let a = 1;
let p = (3, 4);
println!("{}", pick(&a, &p));
}
A value behind a Box parameter:
fn pick<'a>(x: &'a i32, y: &Box<i32>) -> &'a i32 {
let _ = x;
&**y
}
fn main() {
let a = 1;
let b = Box::new(2);
println!("{}", pick(&a, &b));
}
An element of an array parameter:
fn pick<'a>(x: &'a i32, arr: &[i32; 2]) -> &'a i32 {
let _ = x;
&arr[1]
}
fn main() {
let a = 1;
let arr = [5, 6];
println!("{}", pick(&a, &arr));
}
A value wrapped in Some on the way out - the wrapping does not change whose data it is:
fn pick<'a>(x: &'a i32, y: &i32) -> &'a i32 {
let _ = x;
Some(y).unwrap()
}
fn main() {
let a = 1;
let b = 2;
println!("{}", pick(&a, &b));
}
A reference to a reference - dereferencing reaches the untied parameter's data:
fn pick<'a>(x: &'a i32, y: &&i32) -> &'a i32 {
let _ = x;
*y
}
fn main() {
let a = 1;
let b = 2;
let rb = &b;
println!("{}", pick(&a, &rb));
}
When tying the parameter is the wrong fix
The eleven fixes above all widen the signature's demand: every caller must now keep both arguments alive for 'a. Two repairs go the other way, and both keep the original signature of the first family.
Return only the data the signature already promises. If the untied parameter was never meant to be returned, the body - not the signature - is what is wrong:
fn foo<'a>(x: &'a i32, y: &i32) -> &'a i32 {
let _ = y;
x
}
fn main() {
let a = 1;
let b = 2;
println!("{}", foo(&a, &b));
}
$ rustc --edition 2021 alt_return_tied.rs -o alt_return_tied
$ ./alt_return_tied
1
The output is 1. The second parameter is still accepted and can still be read, compared, or logged; it simply never flows to the return, so its type needs no lifetime.
Return an owned value instead. If no borrow needs to survive the call, dropping the reference from the return type removes the promise entirely:
fn foo(x: &i32, y: &i32) -> i32 {
if x > y { *x } else { *y }
}
fn main() {
let a = 1;
let b = 2;
println!("{}", foo(&a, &b));
}
$ rustc --edition 2021 alt_owned.rs -o alt_owned
$ ./alt_owned
2
The output is 2. With no lifetime in the signature there is nothing for a parameter to be tied to, and E0621 cannot arise - at the price of copying the value out, which for an i32 is nothing and for a large value is a real design choice.
The neighbors that compile
These programs return references with no explicit lifetime anywhere, and compile as written - each is a shape elision covers completely.
A single input parameter: under the elision rules, the one input lifetime is assigned to the output, so the returned element reference is tied automatically:
fn first(vals: &[i32]) -> &i32 {
&vals[0]
}
fn main() {
let v = [1, 2, 3];
println!("{}", first(&v));
}
$ rustc --edition 2021 ok_elided_single.rs -o ok_elided_single
$ ./ok_elided_single
1
The output is 1. One input means there is nothing to choose between, and no promise to contradict.
A method returning data from self: elision assigns the lifetime of &self to the output:
struct H {
name: String,
}
impl H {
fn name(&self) -> &str {
&self.name
}
}
fn main() {
let h = H { name: String::from("n") };
println!("{}", h.name());
}
$ rustc --edition 2021 ok_self_method.rs -o ok_self_method
$ ./ok_self_method
n
The output is n. The sixth family failed only because its method returned a different parameter than the one elision - and its explicit annotation - tied the output to.
A 'static return: data that lives for the entire program needs no input to borrow from:
fn greet() -> &'static str {
"hi"
}
fn main() {
println!("{}", greet());
}
$ rustc --edition 2021 ok_static.rs -o ok_static
$ ./ok_static
hi
The output is hi. A string literal is 'static, so the signature's promise is kept by the data itself rather than by any parameter.
The fixes in reach order
- Read the parameter named in the header. It is the parameter the returned data flows from, and it - not the return statement - is where the repair lands.
- The function should be able to return either parameter's data: add the named lifetime to that parameter's type, as the diagnostic's help already writes it.
- The function should only ever return the tied parameter's data: change the body so the untied parameter never reaches a return, a
matcharm, or a call that returns it. - No borrow needs to outlive the call: return an owned value and remove the lifetime from the signature.
- The named parameter is a container - a slice, a
Vec, an array, a struct: the lifetime belongs on the container's parameter, because element and field references borrow the container. - The header is not E0621: a "missing lifetime specifier" header is E0106 and a "does not live long enough" header is E0597 - both in the traps, both fixed elsewhere than the signature's parameter types.
Traps
- No named lifetime at all is E0106, not E0621. A function returning a borrowed value with no parameter to borrow it from has no lifetime to tie anything to:
fn foo() -> &str {
"hi"
}
fn main() {
println!("{}", foo());
}
$ rustc --edition 2021 trap_e0106.rs -o trap_e0106
error[E0106]: missing lifetime specifier
--> trap_e0106.rs:1:13
|
1 | fn foo() -> &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
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 foo() -> &'static str {
| +++++++
help: instead, you are more likely to want to return an owned value
|
1 - fn foo() -> &str {
1 + fn foo() -> String {
|
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0106`.
'static, as the help suggests for a literal, or returning an owned String settles it.
- Two inputs and no named lifetime is also E0106. Elision gives each input its own lifetime and then cannot choose one for the output:fn longest(a: &str, b: &str) -> &str {
if a.len() > b.len() { a } else { b }
}
fn main() {
println!("{}", longest("x", "yy"));
}
$ rustc --edition 2021 trap_e0106_two_inputs.rs -o trap_e0106_two_inputs
error[E0106]: missing lifetime specifier
--> trap_e0106_two_inputs.rs:1:33
|
1 | fn longest(a: &str, b: &str) -> &str {
| ---- ---- ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `a` or `b`
help: consider introducing a named lifetime parameter
|
1 | fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
| ++++ ++ ++ ++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0106`.
This is the first family one step earlier: the signature must first name a lifetime - which is what turns this program's error into E0621 until the second parameter is tied to it as well. - A value that ends too soon is E0597, and no signature edit fixes it:
fn main() {
let r;
{
let x = 5;
r = &x;
}
println!("{}", r);
}
$ rustc --edition 2021 trap_e0597.rs -o trap_e0597
error[E0597]: `x` does not live long enough
--> trap_e0597.rs:5:13
|
4 | let x = 5;
| - binding `x` declared here
5 | r = &x;
| ^^ borrowed value does not live long enough
6 | }
| - `x` dropped here while still borrowed
7 | println!("{}", r);
| - borrow later used here
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0597`.
Here every type is local and the signature of main promises nothing; the borrowed value's scope simply ends before the borrow is used. The repair is in the body's scopes - keep the value alive as long as the reference - not in any parameter's type.
- Two different named lifetimes fail without an error code. Giving the second parameter its own lifetime, 'b, does not satisfy a return promised as 'a:
fn pick<'a, 'b>(x: &'a i32, y: &'b i32) -> &'a i32 {
y
}
fn main() {
let a = 1;
let b = 2;
println!("{}", pick(&a, &b));
}
$ rustc --edition 2021 trap_two_named.rs -o trap_two_named
error: lifetime may not live long enough
--> trap_two_named.rs:2:5
|
1 | fn pick<'a, 'b>(x: &'a i32, y: &'b i32) -> &'a i32 {
| -- -- lifetime `'b` defined here
| |
| lifetime `'a` defined here
2 | y
| ^ function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'b`
|
= help: consider adding the following bound: `'b: 'a`
warning: unused variable: `x`
--> trap_two_named.rs:1:17
|
1 | fn pick<'a, 'b>(x: &'a i32, y: &'b i32) -> &'a i32 {
| ^ help: if this is intentional, prefix it with an underscore: `_x`
|
= note: `#[warn(unused_variables)]` (part of `#[warn(unused)]`) on by default
error: aborting due to 1 previous error; 1 warning emitted
The message is an uncoded "lifetime may not live long enough": the compiler now knows both lifetimes and knows 'b is not 'a, rather than knowing one and missing the other. Naming a lifetime is not the fix - naming the same lifetime is.
Checklist
- The parameter named in the header identified, and the return paths in the body traced to the data each one returns.
- Every parameter whose data can reach the return carrying the same named lifetime as the return type, or a lifetime proven to outlive it -
'static, or a second lifetime bound to outlive it such as'b: 'a. - Container parameters - slices, vectors, arrays, structs - tied as containers, since element and field references borrow them whole.
matchandifarms checked individually: one untied arm fails the whole function.- Where the signature's demand would be too strong for callers, the body narrowed to the tied parameter, or the return changed to an owned value, instead of tying.
- Elision left alone where it already covers the shape: one input, or a method returning
self's data. - The header checked before the repair: E0621 for an untied parameter under a named lifetime, E0106 when no lifetime is named yet, E0597 when the data itself ends too soon.
- The fixed program run, and its output checked against what the program was meant to print.
Related guides on this site
- E0040 Explicit Destructor Call Fix
- E0261 Undeclared Lifetime Name Fix
- E0623 Lifetime Mismatch Fix
- E0106 Missing Lifetime Fix
Sources
- Rust, Error codes index: E0621 — for the definition of the error as a mismatch between the lifetimes in the function signature and the data-flow in the body, for its example of a function returning
&'a i32from an untied second parameter, and for its two repairs, updating the signature or changing the body to not return data from the untied parameter. - The Rust Reference, Lifetime elision — for the elision rules: each elided input lifetime becomes its own parameter, a single input lifetime is assigned to all elided outputs, and the lifetime of
&selfor&mut selfis assigned to elided outputs in methods. - The Rust Reference, Lifetimes — for reference types carrying a lifetime that bounds how long the referent must remain valid.
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.