Rust

E0521 Borrowed Data Escapes Closure Fix

E0521 is the closure lifetime error: a closure parameter carries a type annotation, the annotation gives the parameter a lifetime of its own, and the closure then stores that reference somewhere that outlives the call - a Vec, a map, a field it captured. The stored reference would outlive the borrow it came from. This guide separates the eleven shapes that produce it, matches each one to the repair that fits it, and draws the line against the neighboring lifetime errors that mention closures and borrows but are not this one.

Written November 25, 2026 · Tested with Rust 1.99.1 · 37 min read

By the end of this guide
  • The rule underneath: the annotation declares a lifetime
  • How to read the diagnostic
  • The first failure: an annotated parameter pushed into a captured Vec
  • The second failure: an annotated parameter assigned to a captured slot

Written November 25, 2026

Tested with Rust 1.99.1

What this guide is

Error E0521 is the closure escape error. The error codes index gives it one sentence - borrowed data escapes outside of closure - and one example: a Vec<&str> outside a closure, and a closure with an annotated parameter, |el: &str|, pushing that parameter into the Vec. Every failure in this guide has that same skeleton. A place that lives outside the closure - a container, a slot, a field - holds references. A closure takes a reference as a parameter and stores the parameter in that place. The store is the escape: when the call ends, the parameter's borrow ends with it, but the place still holds the reference.

The annotation is what makes it an error rather than a working program. The index states the mechanism directly: a type annotation of a closure parameter implies a new lifetime declaration. Written as &str with no lifetime, the parameter's reference gets a fresh lifetime that belongs to the closure's signature alone, and nothing ties that lifetime to the captured place the reference is stored in - so the compiler cannot show that the stored reference stays valid, and it refuses the store. Remove the annotation and the compiler infers the parameter type from the body, tying the parameter's lifetime to the capture's in a single inference, and the same program compiles. That is why the Book's closure chapter treats annotation as optional decoration: closures are used in a narrow context, their parameter and return types are inferred, and annotations are added only for explicitness. Here the decoration changes the meaning.

The repairs fall into two groups. Drop the annotation, and let inference tie the lifetimes together - the repair the index itself gives for its example. Or keep the annotation and change what is stored: an owned String in place of the &str, a copy in place of a reference to a Copy value, so nothing borrowed is stored at all. A third route, for code that genuinely needs the signature written out, is to leave closures behind for that operation and write a function with a named lifetime shared by the container and the parameter; it is in the alternatives below. Which repair fits depends on whether the stored values have to be references, and the diagnostic identifies the two parties - the escaping parameter and the outside place - so reading it comes first.

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: the annotation declares a lifetime

A closure parameter annotation is not a comment about a type the compiler would have picked anyway. Per the error codes index, it implies a new lifetime declaration: |el: &str| says the parameter is a reference with some lifetime, and that lifetime is chosen for the closure's signature, fresh, with no relation to anything the closure captured. The captured Vec has its own lifetime for the references it holds, fixed by where the Vec is declared and what is later done with it. Storing the parameter in the Vec asks the compiler to prove the parameter's fresh lifetime covers the Vec's - and by construction it cannot, because the two were never tied together.

Without the annotation, there is no second lifetime to tie. The compiler infers the closure's signature from its whole context - the body, the captures, and the calls - under the lifetime elision and inference rules the index points to, and it infers one arrangement in which the parameter's lifetime and the captured Vec's element lifetime are the same. The Reference describes the other half of the picture: a closure captures its environment, preferring shared references and taking mutable references where the body needs them, so the Vec the parameter escapes into is a mutable capture whose own borrow of the outside variable lasts as long as the closure does. The escape is judged against that whole arrangement, not against the push alone.

Two consequences follow, and both appear below. First, the error does not depend on what the container is: a Vec, a map key set, a struct field, a Cell, a RefCell interior - the outside place differs, the untied lifetimes are the same, and the code is E0521 in every case. Second, the error does not depend on the call: several failures below are called only with string literals, which live for the whole program, and they still fail - the signature alone, not any call's argument, is what cannot be justified. Where a program without the annotation does fail on a call, the error is a different one, and it is in the traps.

How to read the diagnostic

Every family in this guide prints the same header - error E0521, "borrowed data escapes outside of closure" - with the span on the statement that stores the parameter, and three labels that name the parties. The first family's, in full:

Terminal
$ rustc --edition 2021 fail_vec_str.rs -o fail_vec_str
error[E0521]: borrowed data escapes outside of closure
 --> fail_vec_str.rs:1:78
  |
1 | fn main() { let mut list: Vec<&str> = Vec::new(); let mut add = |el: &str| { list.push(el); }; add("hi"); println!("{}", list.len()); }
  |                 --------                                         --          ^^^^^^^^^^^^^ `el` escapes the closure body here
  |                 |                                                |
  |                 |                                                `el` is a reference that is only valid in the closure body
  |                 `list` declared here, outside of the closure body
  |
  = note: requirement occurs because of a mutable reference to `Vec<&str>`
  = note: mutable references are invariant over their type parameter
  = help: see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0521`.

Read it in order. The header names the offense, not the parties. The labels are where the information is: the storing statement is underlined with "el escapes the closure body here", the parameter is labeled "a reference that is only valid in the closure body", and the captured variable is labeled "declared here, outside of the closure body". Those three labels are the whole diagnosis - a reference valid only inside the body has been placed somewhere declared outside it. Most families add the same notes after the labels - that the requirement occurs because of a mutable reference to the outside place, and that mutable references are invariant over their type parameter. The slot-assignment family carries no notes at all, and the RefCell and Cell families name their cell type in the notes instead; the labels are unchanged in every family. The reading above is scoped to the forms printed in this guide.

The first failure: an annotated parameter pushed into a captured Vec

The example from the error codes index, with the closure called and the Vec read back:

Rust
fn main() { let mut list: Vec<&str> = Vec::new(); let mut add = |el: &str| { list.push(el); }; add("hi"); println!("{}", list.len()); }
Terminal
$ rustc --edition 2021 fail_vec_str.rs -o fail_vec_str
error[E0521]: borrowed data escapes outside of closure
 --> fail_vec_str.rs:1:78
  |
1 | fn main() { let mut list: Vec<&str> = Vec::new(); let mut add = |el: &str| { list.push(el); }; add("hi"); println!("{}", list.len()); }
  |                 --------                                         --          ^^^^^^^^^^^^^ `el` escapes the closure body here
  |                 |                                                |
  |                 |                                                `el` is a reference that is only valid in the closure body
  |                 `list` declared here, outside of the closure body
  |
  = note: requirement occurs because of a mutable reference to `Vec<&str>`
  = note: mutable references are invariant over their type parameter
  = help: see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0521`.
Rust
fn main() { let mut list: Vec<&str> = Vec::new(); let mut add = |el| { list.push(el); }; add("hi"); println!("{}", list[0]); }
Terminal
$ rustc --edition 2021 fix_vec_str.rs -o fix_vec_str
$ ./fix_vec_str
hi

The closure captures list mutably and pushes its parameter into it. The parameter is annotated &str, so it carries the fresh lifetime the annotation declares; list is declared outside the closure and keeps whatever is pushed into it after the call returns. The push is the escape, and the span sits on it. The fix is the index's own: the annotation comes off, the compiler infers the parameter as the reference type the Vec holds, with the lifetimes tied, and the program runs.

The output is hi, the element read back out of the Vec. Nothing else in the program changes - the capture, the push, and the call are identical; only the annotation is gone.

The second failure: an annotated parameter assigned to a captured slot

A single reference variable outside the closure, assigned from inside it:

Rust
fn main() { let mut slot: &str = ""; let mut set = |s: &str| { slot = s; }; set("hi"); println!("{}", slot); }
Terminal
$ rustc --edition 2021 fail_assign_slot.rs -o fail_assign_slot
error[E0521]: borrowed data escapes outside of closure
 --> fail_assign_slot.rs:1:64
  |
1 | fn main() { let mut slot: &str = ""; let mut set = |s: &str| { slot = s; }; set("hi"); println!("{}", slot); }
  |                 --------                            -          ^^^^^^^^ `s` escapes the closure body here
  |                 |                                   |
  |                 |                                   `s` is a reference that is only valid in the closure body
  |                 `slot` declared here, outside of the closure body

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0521`.
Rust
fn main() { let mut slot = String::new(); let mut set = |s: &str| { slot = s.to_string(); }; set("hi"); println!("{}", slot); }
Terminal
$ rustc --edition 2021 fix_assign_slot.rs -o fix_assign_slot
$ ./fix_assign_slot
hi

No container is involved. slot is one &str declared outside the closure, and the assignment slot = s stores the parameter in it - the same escape with the smallest possible outside place. The labels name slot as the outside declaration and s as the reference valid only in the body. The fix keeps the annotation and changes what is stored: slot becomes a String, and the closure stores a copy of the text it was given. Nothing borrowed leaves the body, so there is nothing to tie.

The output is hi. This is the repair to reach for when the signature has to stay explicit - the annotation survives, the stored value stops being a reference.

The third failure: an annotated parameter as a map key

A HashMap captured by the closure that inserts into it:

Rust
use std::collections::HashMap; fn main() { let mut m: HashMap<&str, i32> = HashMap::new(); let mut put = |k: &str| { m.insert(k, 1); }; put("a"); println!("{}", m.len()); }
Terminal
$ rustc --edition 2021 fail_hashmap_key.rs -o fail_hashmap_key
error[E0521]: borrowed data escapes outside of closure
 --> fail_hashmap_key.rs:1:118
  |
1 | ...{ let mut m: HashMap<&str, i32> = HashMap::new(); let mut put = |k: &str| { m.insert(k, 1); }; put("a"); println!("{}", m.len()); }
  |          -----                                                      -          ^^^^^^^^^^^^^^ `k` escapes the closure body here
  |          |                                                          |
  |          `m` declared here, outside of the closure body             `k` is a reference that is only valid in the closure body
  |
  = note: requirement occurs because of a mutable reference to `HashMap<&str, i32>`
  = note: mutable references are invariant over their type parameter
  = help: see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0521`.
Rust
use std::collections::HashMap; fn main() { let mut m: HashMap<String, i32> = HashMap::new(); let mut put = |k: &str| { m.insert(k.to_string(), 1); }; put("a"); println!("{}", m.len()); }
Terminal
$ rustc --edition 2021 fix_hashmap_key.rs -o fix_hashmap_key
$ ./fix_hashmap_key
1

The map holds &str keys, and insert stores the annotated parameter as a key. A map entry is an outside place in the same way a Vec element is: it persists after the call, holding the reference. The span sits on the insert. The fix stores owned keys - the map becomes HashMap<String, i32> and the closure inserts a String made from its parameter. The parameter keeps its annotation; the key the map keeps is a copy.

The output is 1, the number of entries. The same shape with the reference in the value position instead of the key position fails identically - the position inside the entry does not matter, the store does.

The fourth failure: an annotated parameter pushed into a struct field

The outside place is a field of a struct the closure captures:

Rust
struct Bag<'a> { items: Vec<&'a str> } fn main() { let mut bag = Bag { items: Vec::new() }; let mut add = |el: &str| { bag.items.push(el); }; add("hi"); println!("{}", bag.items.len()); }
Terminal
$ rustc --edition 2021 fail_struct_field.rs -o fail_struct_field
error[E0521]: borrowed data escapes outside of closure
 --> fail_struct_field.rs:1:120
  |
1 | ...{ let mut bag = Bag { items: Vec::new() }; let mut add = |el: &str| { bag.items.push(el); }; add("hi"); println!("{}", bag.items.l...
  |          -------                                             --          ^^^^^^^^^^^^^^^^^^ `el` escapes the closure body here
  |          |                                                   |
  |          |                                                   `el` is a reference that is only valid in the closure body
  |          `bag` declared here, outside of the closure body
  |
  = note: requirement occurs because of a mutable reference to `Vec<&str>`
  = note: mutable references are invariant over their type parameter
  = help: see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0521`.
Rust
struct Bag<'a> { items: Vec<&'a str> } fn main() { let mut bag = Bag { items: Vec::new() }; let mut add = |el| { bag.items.push(el); }; add("hi"); println!("{}", bag.items[0]); }
Terminal
$ rustc --edition 2021 fix_struct_field.rs -o fix_struct_field
$ ./fix_struct_field
hi

Bag declares its own lifetime for the references its items field holds, and the closure captures bag and pushes its annotated parameter into that field. The field's lifetime comes from the struct definition; the parameter's comes from the annotation; the two are unrelated, and the push is refused. The fix drops the annotation, and inference ties the parameter to the field's lifetime through the capture - the struct keeps its declared lifetime, and the closure's parameter is inferred against it.

The output is hi, the element read back through the field. Naming a lifetime on the struct does not rescue the annotated closure - the struct's lifetime was never the missing piece; the tie between the parameter and the capture was.

The fifth failure: two annotated parameters, both stored

A closure with two reference parameters that stores both of them:

Rust
fn main() { let mut list: Vec<&str> = Vec::new(); let mut add = |a: &str, b: &str| { list.push(a); list.push(b); }; add("x", "y"); println!("{}", list.len()); }
Terminal
$ rustc --edition 2021 fail_two_params.rs -o fail_two_params
error[E0521]: borrowed data escapes outside of closure
 --> fail_two_params.rs:1:86
  |
1 | ... { let mut list: Vec<&str> = Vec::new(); let mut add = |a: &str, b: &str| { list.push(a); list.push(b); }; add("x", "y"); println!...
  |           --------                                         -                   ^^^^^^^^^^^^ `a` escapes the closure body here
  |           |                                                |
  |           |                                                `a` is a reference that is only valid in the closure body
  |           `list` declared here, outside of the closure body
  |
  = note: requirement occurs because of a mutable reference to `Vec<&str>`
  = note: mutable references are invariant over their type parameter
  = help: see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance

error[E0521]: borrowed data escapes outside of closure
 --> fail_two_params.rs:1:100
  |
1 | fn main() { let mut list: Vec<&str> = Vec::new(); let mut add = |a: &str, b: &str| { list.push(a); list.push(b); }; add("x", "y"); pr...
  |                 --------                                                  -                        ^^^^^^^^^^^^ `b` escapes the closure body here
  |                 |                                                         |
  |                 |                                                         `b` is a reference that is only valid in the closure body
  |                 `list` declared here, outside of the closure body
  |
  = note: requirement occurs because of a mutable reference to `Vec<&str>`
  = note: mutable references are invariant over their type parameter
  = help: see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0521`.
Rust
fn main() { let mut list: Vec<&str> = Vec::new(); let mut add = |a, b| { list.push(a); list.push(b); }; add("x", "y"); println!("{}", list.len()); }
Terminal
$ rustc --edition 2021 fix_two_params.rs -o fix_two_params
$ ./fix_two_params
2

Each annotated parameter declares its own fresh lifetime, and each push is an escape. The compiler reports each store separately - two errors, one per parameter, as the transcript above shows; removing one push would leave the other failing the same way. The fix drops both annotations, and inference gives both parameters the lifetime the Vec's elements need.

The output is 2 - both elements stored. With several parameters, the annotation count is what multiplies: every annotated reference parameter that reaches an outside place is a separate untied lifetime, and the compiler reports one error for each parameter stored.

The sixth failure: an annotated slice parameter

The parameter is a reference to a slice rather than to a string:

Rust
fn main() { let mut list: Vec<&[i32]> = Vec::new(); let mut add = |el: &[i32]| { list.push(el); }; add(&[1, 2]); println!("{}", list.len()); }
Terminal
$ rustc --edition 2021 fail_slice_param.rs -o fail_slice_param
error[E0521]: borrowed data escapes outside of closure
 --> fail_slice_param.rs:1:82
  |
1 | fn main() { let mut list: Vec<&[i32]> = Vec::new(); let mut add = |el: &[i32]| { list.push(el); }; add(&[1, 2]); println!("{}", list....
  |                 --------                                           --            ^^^^^^^^^^^^^ `el` escapes the closure body here
  |                 |                                                  |
  |                 |                                                  `el` is a reference that is only valid in the closure body
  |                 `list` declared here, outside of the closure body
  |
  = note: requirement occurs because of a mutable reference to `Vec<&[i32]>`
  = note: mutable references are invariant over their type parameter
  = help: see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0521`.
Rust
fn main() { let mut list: Vec<Vec<i32>> = Vec::new(); let mut add = |el: &[i32]| { list.push(el.to_vec()); }; add(&[1, 2]); println!("{}", list[0].len()); }
Terminal
$ rustc --edition 2021 fix_slice_param.rs -o fix_slice_param
$ ./fix_slice_param
2

&[i32] is a reference like any other, and the Vec of slice references is an outside place like any other. The annotation declares the slice's lifetime for the signature alone, and the push stores it past the call. The fix stores the slice's contents instead: the Vec holds Vec<i32> values, and the closure pushes a copy of the slice it was given, keeping its annotation.

The output is 2, the length of the stored copy. Element type does not enter into the error - a reference to a slice, a reference to a string, and a reference to a number all escape the same way, which the extra shapes below confirm for &i32.

The seventh failure: an annotated String reference

The parameter is a reference to a heap string, and the call passes a named variable:

Rust
fn main() { let mut list: Vec<&String> = Vec::new(); let mut add = |el: &String| { list.push(el); }; let s = String::from("hi"); add(&s); println!("{}", list[0]); }
Terminal
$ rustc --edition 2021 fail_string_ref.rs -o fail_string_ref
error[E0521]: borrowed data escapes outside of closure
 --> fail_string_ref.rs:1:84
  |
1 | ... { let mut list: Vec<&String> = Vec::new(); let mut add = |el: &String| { list.push(el); }; let s = String::from("hi"); add(&s); p...
  |           --------                                            --             ^^^^^^^^^^^^^ `el` escapes the closure body here
  |           |                                                   |
  |           |                                                   `el` is a reference that is only valid in the closure body
  |           `list` declared here, outside of the closure body
  |
  = note: requirement occurs because of a mutable reference to `Vec<&String>`
  = note: mutable references are invariant over their type parameter
  = help: see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0521`.
Rust
fn main() { let mut list: Vec<&String> = Vec::new(); let mut add = |el| { list.push(el); }; let s = String::from("hi"); add(&s); println!("{}", list[0]); }
Terminal
$ rustc --edition 2021 fix_string_ref.rs -o fix_string_ref
$ ./fix_string_ref
hi

This is the form the escape takes in ordinary code: the argument, &s, plainly outlives the Vec - s is declared before it and read after - and the program still fails. The failure is in the signature, not in the call: the annotation's fresh lifetime is untied no matter how long any particular argument lives, so the compiler refuses the store without examining the call site. The fix drops the annotation, and with the lifetimes inferred together, the same call and the same read-back compile.

The output is hi. When a program like this fails, do not reach for a longer-lived argument - the argument was never the problem, and the traps below show the different error a genuinely short-lived argument produces.

The eighth failure: a Vec inside a RefCell

The container sits behind interior mutability, and the closure takes only a shared capture of it:

Rust
use std::cell::RefCell; fn main() { let list = RefCell::new(Vec::new()); let add = |el: &str| { list.borrow_mut().push(el); }; add("hi"); println!("{}", list.borrow().len()); }
Terminal
$ rustc --edition 2021 fail_refcell.rs -o fail_refcell
error[E0521]: borrowed data escapes outside of closure
 --> fail_refcell.rs:1:97
  |
1 | ...in() { let list = RefCell::new(Vec::new()); let add = |el: &str| { list.borrow_mut().push(el); }; add("hi"); println!("{}", list.b...
  |               ----                                        --          ^^^^^^^^^^^^^^^^^ `el` escapes the closure body here
  |               |                                           |
  |               |                                           `el` is a reference that is only valid in the closure body
  |               `list` declared here, outside of the closure body
  |
  = note: requirement occurs because of the type `RefCell<Vec<&str>>`, which makes the generic argument `Vec<&str>` invariant
  = note: the struct `RefCell<T>` is invariant over the parameter `T`
  = help: see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0521`.
Rust
use std::cell::RefCell; fn main() { let list = RefCell::new(Vec::new()); let add = |el| { list.borrow_mut().push(el); }; add("hi"); println!("{}", list.borrow()[0]); }
Terminal
$ rustc --edition 2021 fix_refcell.rs -o fix_refcell
$ ./fix_refcell
hi

RefCell changes how the Vec is borrowed, not how long its contents live. The closure captures the RefCell by reference, borrows it mutably for the push, and stores the annotated parameter in the Vec inside - an outside place reached through one more layer, still outside. The span sits on the push, and the labels are the usual three. The fix drops the annotation; the borrow_mut call and the capture are unchanged.

The output is hi, read back through a shared borrow. Interior mutability is a borrowing mechanism, not a lifetime mechanism - it moves the borrow check to run time and leaves the escape exactly where it was.

The ninth failure: a reference set into a Cell

The smallest outside place of all - one Cell holding one reference:

Rust
use std::cell::Cell; fn main() { let slot: Cell<&str> = Cell::new(""); let set = |s: &str| { slot.set(s); }; set("hi"); println!("{}", slot.get()); }
Terminal
$ rustc --edition 2021 fail_cell_slot.rs -o fail_cell_slot
error[E0521]: borrowed data escapes outside of closure
 --> fail_cell_slot.rs:1:94
  |
1 | ...main() { let slot: Cell<&str> = Cell::new(""); let set = |s: &str| { slot.set(s); }; set("hi"); println!("{}", slot.get()); }
  |                 ----                                         -          ^^^^^^^^^^^ `s` escapes the closure body here
  |                 |                                            |
  |                 |                                            `s` is a reference that is only valid in the closure body
  |                 `slot` declared here, outside of the closure body
  |
  = note: requirement occurs because of the type `Cell<&str>`, which makes the generic argument `&str` invariant
  = note: the struct `Cell<T>` is invariant over the parameter `T`
  = help: see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0521`.
Rust
use std::cell::Cell; fn main() { let slot: Cell<&str> = Cell::new(""); let set = |s| { slot.set(s); }; set("hi"); println!("{}", slot.get()); }
Terminal
$ rustc --edition 2021 fix_cell_slot.rs -o fix_cell_slot
$ ./fix_cell_slot
hi

Cell stores the reference by copy, with no borrow held at all, and the escape still happens: set places the annotated parameter's reference in a cell declared outside the closure, where it remains after the call. The diagnostic is the same three labels over the set call. The fix drops the annotation, and inference ties the parameter to the cell's element lifetime.

The output is hi. Together with the second family, this is the pattern to recognize: the outside place can be a single variable or a single cell, and the error is unchanged - the size of the place never mattered, only that it is outside the body and holds the reference past the call.

The tenth failure: the same push inside a thread scope

The Vec and the storing closure both sit inside a thread::scope closure:

Rust
fn main() { let mut list: Vec<&str> = Vec::new(); std::thread::scope(|_s| { let mut add = |el: &str| { list.push(el); }; add("hi"); }); println!("{}", list.len()); }
Terminal
$ rustc --edition 2021 fail_thread_scope.rs -o fail_thread_scope
error[E0521]: borrowed data escapes outside of closure
 --> fail_thread_scope.rs:1:104
  |
1 | ...in() { let mut list: Vec<&str> = Vec::new(); std::thread::scope(|_s| { let mut add = |el: &str| { list.push(el); }; add("hi"); });...
  |               --------                                                                   --          ^^^^^^^^^^^^^ `el` escapes the closure body here
  |               |                                                                          |
  |               `list` declared here, outside of the closure body                          `el` is a reference that is only valid in the closure body
  |
  = note: requirement occurs because of a mutable reference to `Vec<&str>`
  = note: mutable references are invariant over their type parameter
  = help: see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0521`.
Rust
fn main() { let mut list: Vec<&str> = Vec::new(); std::thread::scope(|_s| { let mut add = |el| { list.push(el); }; add("hi"); }); println!("{}", list[0]); }
Terminal
$ rustc --edition 2021 fix_thread_scope.rs -o fix_thread_scope
$ ./fix_thread_scope
hi

Nesting the whole arrangement inside another closure changes nothing about the inner one. The inner closure's parameter is annotated, its captured Vec is declared outside it - inside the scope closure, but outside the storing closure, which is the boundary the error measures - and the push escapes across that boundary. This family's transcript carries the standard notes visible above, about the mutable reference to the Vec and invariance; the header, the span, and the three labels are the standard ones. The fix drops the inner annotation, exactly as in the first family.

The output is hi. A scoped thread's closure is not a shelter for the escape: the rule is about the closure that does the storing, wherever that closure itself is written.

The eleventh failure: a storing closure that returns a value

The closure stores its parameter and returns the Vec's length:

Rust
fn main() { let mut list: Vec<&str> = Vec::new(); let mut add = |el: &str| -> usize { list.push(el); list.len() }; println!("{}", add("hi")); }
Terminal
$ rustc --edition 2021 fail_return_store.rs -o fail_return_store
error[E0521]: borrowed data escapes outside of closure
 --> fail_return_store.rs:1:87
  |
1 | ...{ let mut list: Vec<&str> = Vec::new(); let mut add = |el: &str| -> usize { list.push(el); list.len() }; println!("{}", add("hi")); }
  |          --------                                         --                   ^^^^^^^^^^^^^ `el` escapes the closure body here
  |          |                                                |
  |          |                                                `el` is a reference that is only valid in the closure body
  |          `list` declared here, outside of the closure body
  |
  = note: requirement occurs because of a mutable reference to `Vec<&str>`
  = note: mutable references are invariant over their type parameter
  = help: see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0521`.
Rust
fn main() { let mut list: Vec<&str> = Vec::new(); let mut add = |el| -> usize { list.push(el); list.len() }; println!("{}", add("hi")); }
Terminal
$ rustc --edition 2021 fix_return_store.rs -o fix_return_store
$ ./fix_return_store
1

The return annotation, -> usize, is not the problem - a count is a plain value, and nothing borrowed is returned. The store in the body is the escape, and the span sits on the push, not on the return. This family separates the two annotations a closure can carry: a return-type annotation on a value type is inert here, while the parameter annotation is what declares the untied lifetime. The fix drops the parameter annotation and keeps the return annotation, and the program compiles with it in place.

The output is 1. A closure may annotate its return freely when the return is a value; the traps below show what an annotated reference return does instead - and it is not E0521.

Seven more shapes that fail the same way

The same header - "borrowed data escapes outside of closure" with code E0521, exactly one error and no other code - for seven more programs. Each is repaired by the same moves as the families above: drop the parameter annotation, or store an owned value:

An annotated reference to a number, pushed into a captured Vec of number references:

Rust
fn main() { let x = 5; let mut list: Vec<&i32> = Vec::new(); let mut add = |el: &i32| { list.push(el); }; add(&x); println!("{}", list.len()); }

A captured set, filled by an annotated key parameter:

Rust
use std::collections::BTreeSet; fn main() { let mut s: BTreeSet<&str> = BTreeSet::new(); let mut put = |k: &str| { s.insert(k); }; put("a"); println!("{}", s.len()); }

An annotated parameter assigned into one field of a captured tuple:

Rust
fn main() { let mut pair: (&str, i32) = ("", 0); let mut set = |s: &str| { pair.0 = s; }; set("hi"); println!("{}", pair.0); }

An annotated parameter assigned into one slot of a captured array:

Rust
fn main() { let mut arr: [&str; 2] = ["", ""]; let mut set = |s: &str| { arr[0] = s; }; set("hi"); println!("{}", arr[0]); }

An annotated parameter assigned through a dereference into a captured box:

Rust
fn main() { let mut slot: Box<&str> = Box::new(""); let mut set = |s: &str| { *slot = s; }; set("hi"); println!("{}", slot); }

A captured double-ended queue, filled at the back by an annotated parameter:

Rust
use std::collections::VecDeque; fn main() { let mut q: VecDeque<&str> = VecDeque::new(); let mut add = |el: &str| { q.push_back(el); }; add("hi"); println!("{}", q.len()); }

An annotated mutable reference parameter, dereferenced and stored:

Rust
fn main() { let mut list: Vec<&str> = Vec::new(); let mut x = "a"; let mut add = |el: &mut &str| { list.push(*el); }; add(&mut x); println!("{}", list.len()); }

When the signature has to be written out

A function with a named lifetime is the genuinely different repair, and it is the first family's operation restated outside a closure. Where the storing operation is shared, named, or part of an interface - the places closures are not used - the tie the annotation failed to make can be written explicitly: one lifetime, 'a, declared on the function, used for both the container's elements and the parameter:

Rust
fn add<'a>(list: &mut Vec<&'a str>, el: &'a str) { list.push(el); } fn main() { let mut list: Vec<&str> = Vec::new(); add(&mut list, "hi"); println!("{}", list[0]); }
Terminal
$ rustc --edition 2021 alt_explicit_fn.rs -o alt_explicit_fn
$ ./alt_explicit_fn
hi

The output is hi. The trade is the usual one: the function is reusable and its contract is explicit, but it has to be named, declared, and called as a function - it cannot capture the Vec the way the closure did, so the Vec travels as a parameter. Choose it when the operation outgrows the closure; choose the dropped annotation when the closure is the right shape and only its decoration was wrong.

The neighbors that compile

These programs sit one item away from the failures and compile as written, each because the parameter's lifetime is inferred rather than annotated, the stored value is owned, or nothing is stored outside the body at all.

The first family's program with no annotation - the baseline every family above deviates from by one annotation:

Rust
fn main() { let mut list: Vec<&str> = Vec::new(); let mut add = |el| { list.push(el); }; add("hi"); println!("{}", list[0]); }
Terminal
$ rustc --edition 2021 ok_unannotated.rs -o ok_unannotated
$ ./ok_unannotated
hi

The output is hi.

An annotated parameter stored as an owned value - the second family's repair, standing on its own:

Rust
fn main() { let mut list: Vec<String> = Vec::new(); let mut add = |el: &str| { list.push(el.to_string()); }; add("hi"); println!("{}", list[0]); }
Terminal
$ rustc --edition 2021 ok_owned_string.rs -o ok_owned_string
$ ./ok_owned_string
hi

The output is hi. The annotation is present and harmless, because the Vec holds String values and the reference itself never leaves the body.

An annotated reference to a Copy value, stored by value:

Rust
fn main() { let mut list: Vec<i32> = Vec::new(); let mut add = |el: &i32| { list.push(*el); }; add(&5); println!("{}", list[0]); }
Terminal
$ rustc --edition 2021 ok_copy_i32.rs -o ok_copy_i32
$ ./ok_copy_i32
5

The output is 5. Dereferencing the parameter copies the number, and a copy is not a borrow - there is no reference in the Vec to escape.

An annotated 'static parameter stored in a Vec of 'static references:

Rust
fn main() { let mut list: Vec<&'static str> = Vec::new(); let mut add = |el: &'static str| { list.push(el); }; add("hi"); println!("{}", list[0]); }
Terminal
$ rustc --edition 2021 ok_static_param.rs -o ok_static_param
$ ./ok_static_param
hi

The output is hi. Here the annotation names a lifetime instead of leaving one to be declared fresh, and the named lifetime is the one the Vec holds - the tie is written in the annotation itself. It works only because every argument must then be a 'static reference, which in practice means literals and leaked or static data.

An annotated parameter that is only read inside the body:

Rust
fn main() { let mut count = 0; let mut add = |el: &str| { count += el.len(); }; add("hi"); println!("{}", count); }
Terminal
$ rustc --edition 2021 ok_use_inside.rs -o ok_use_inside
$ ./ok_use_inside
2

The output is 2, the length the closure counted. The parameter's length is added to a captured counter - a value crosses the boundary, not a reference - so there is no escape for the annotation to cause. E0521 needs the store, not merely the annotation and a capture.

An annotated parameter stored in a Vec created inside the body:

Rust
fn main() { let add = |el: &str| { let mut local: Vec<&str> = Vec::new(); local.push(el); local.len() }; println!("{}", add("hi")); }
Terminal
$ rustc --edition 2021 ok_local_vec.rs -o ok_local_vec
$ ./ok_local_vec
1

The output is 1. The Vec is declared inside the closure and dropped when the call ends, so the stored reference never outlives the body - the outside place is what makes the store an escape, and here there is none.

The fixes in reach order

  • The closure is local and its signature is not an interface: drop the parameter annotation. Inference ties the parameter's lifetime to the capture's, and the program compiles unchanged otherwise. The first, fourth, fifth, seventh, eighth, ninth, tenth, and eleventh families.
  • The stored values do not have to be references: store owned values - a String for a &str, a Vec for a slice, a copy for a Copy type - and keep the annotation if it earns its place. The second, third, and sixth families.
  • The annotation names the lifetime the container holds, as with 'static: the tie can be written in the annotation itself, at the cost of restricting every argument to that lifetime. The neighbors show the form.
  • The operation has outgrown the closure: write it as a function with one named lifetime shared by the container and the parameter. The alternatives section.
  • The header is not E0521: a short-lived argument to an unannotated closure is E0597, a reference to a temporary is E0716, an assignment over a live borrow is E0506, a second mutable borrow is E0499, a missing lifetime in a function signature is E0106, and an annotated reference return on a closure carries no code at all - all in the traps.

Traps

  • An unannotated closure called with a reference that dies too soon is E0597, not E0521. The annotation is gone, inference has tied the lifetimes, and now a call can break the tie from the other side: the argument is a borrow of a local String that is dropped while the Vec still holds it:
Rust
fn main() { let mut list: Vec<&str> = Vec::new(); let mut add = |el| { list.push(el); }; { let s = String::from("hi"); add(&s); } println!("{}", list.len()); }
Terminal
$ rustc --edition 2021 trap_short_lived.rs -o trap_short_lived
error[E0597]: `s` does not live long enough
 --> trap_short_lived.rs:1:124
  |
1 | ...et mut list: Vec<&str> = Vec::new(); let mut add = |el| { list.push(el); }; { let s = String::from("hi"); add(&s); } println!("{}", list.le...
  |       --------                                                                       -                           ^^   -                ---- borrow later used here
  |       |                                                                              |                           |    |
  |       |                                                                              |                           |    `s` dropped here while still borrowed
  |       variable `list` declared here                                                  binding `s` declared here   borrowed value does not live long enough
  |
  = note: `list` is a collection that stores borrowed references, but `s` does not live long enough to be stored in it
  = help: buffer reuse with borrowed references requires unsafe code or restructuring

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0597`.
Trap
The repair is the argument's lifetime, not the closure: keep the String alive as long as the Vec is read, or store an owned value. The error codes index states this error as a borrow that does not live long enough - a property of the call, where E0521 is a property of the signature.
  • A Vec holding a reference to a temporary is E0716. No closure is involved; the temporary String is dropped at the end of the statement while the Vec still borrows it:
Rust
fn main() { let v = vec![&String::from("hi")]; println!("{}", v[0]); }
Terminal
$ rustc --edition 2021 trap_temp_vec.rs -o trap_temp_vec
error[E0716]: temporary value dropped while borrowed
 --> trap_temp_vec.rs:1:27
  |
1 | fn main() { let v = vec![&String::from("hi")]; println!("{}", v[0]); }
  |                           ^^^^^^^^^^^^^^^^^^ -                - borrow later used here
  |                           |                  |
  |                           |                  temporary value is freed at the end of this statement
  |                           creates a temporary value which is freed while still in use
  |
help: consider using a `let` binding to create a longer lived value
  |
1 ~ fn main() { let binding = String::from("hi");
2 ~ let v = vec![&binding]; println!("{}", v[0]); }
  |

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0716`.

The repair is to bind the value to a name first, so it lives as long as its borrowers, or to store the value itself. A temporary's lifetime is the statement, and no annotation or inference extends it into the Vec.

  • Assigning to a variable while it is borrowed is E0506. There is no closure and no store of a parameter; the borrow itself blocks the assignment:
Rust
fn main() { let mut x = 5; let r = &x; x = 6; println!("{} {}", x, r); }
Terminal
$ rustc --edition 2021 trap_assign_borrowed.rs -o trap_assign_borrowed
error[E0506]: cannot assign to `x` because it is borrowed
 --> trap_assign_borrowed.rs:1:40
  |
1 | fn main() { let mut x = 5; let r = &x; x = 6; println!("{} {}", x, r); }
  |                                    --  ^^^^^                       - borrow later used here
  |                                    |   |
  |                                    |   `x` is assigned to here but it was already borrowed
  |                                    `x` is borrowed here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0506`.

The repair is to end the borrow before the assignment - use the reference for the last time earlier, or copy the value out of it. The conflict is between the borrow and the write, not between two lifetimes in a signature.

  • Two mutable borrows of the same value at once is E0499:
Rust
fn main() { let mut v = vec![1, 2]; let a = &mut v; let b = &mut v; println!("{:?} {:?}", a, b); }
Terminal
$ rustc --edition 2021 trap_mut_twice.rs -o trap_mut_twice
error[E0499]: cannot borrow `v` as mutable more than once at a time
 --> trap_mut_twice.rs:1:61
  |
1 | fn main() { let mut v = vec![1, 2]; let a = &mut v; let b = &mut v; println!("{:?} {:?}", a, b); }
  |                                             ------          ^^^^^^                        - first borrow later used here
  |                                             |               |
  |                                             |               second mutable borrow occurs here
  |                                             first mutable borrow occurs here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0499`.

The repair is to finish with the first borrow before taking the second, or to split what is borrowed into disjoint parts. This error appears around closures often, because a closure that captures a variable mutably holds a borrow of it - but the code is the plain double-borrow error, and the closure is not the cause.

  • A function that returns a reference without a lifetime the compiler can elide is E0106, missing lifetime specifier. Functions, unlike the closures in this guide, must declare their interfaces, and a two-parameter function returning a reference has no elision rule that picks the source:
Rust
fn longest(x: &str, y: &str) -> &str { if x.len() > y.len() { x } else { y } } fn main() { println!("{}", longest("a", "bb")); }
Terminal
$ rustc --edition 2021 trap_missing_lifetime.rs -o trap_missing_lifetime
error[E0106]: missing lifetime specifier
 --> trap_missing_lifetime.rs:1:33
  |
1 | fn longest(x: &str, y: &str) -> &str { if x.len() > y.len() { x } else { y } } fn main() { println!("{}", longest("a", "bb")); }
  |               ----     ----     ^ 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 `x` or `y`
help: consider introducing a named lifetime parameter
  |
1 | fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } } fn main() { println!("{}", longest("a", "bb")); }
  |           ++++     ++          ++          ++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0106`.

The repair is a named lifetime tying the return to the parameter it comes from. This is the function-side cousin of the closure problem - a lifetime that must be declared rather than inferred - and it is also why the alternative fix above declares 'a explicitly: on a function, the declaration is available and is the repair.

  • A closure with an annotated reference return is an error with no code. Annotating the return as &str gives the return its own fresh lifetime, unrelated to the parameter's, and returning the parameter then fails with the plain message that a lifetime may not live long enough:
Rust
fn main() { let x = String::from("hi"); let get = |s: &str| -> &str { s }; println!("{}", get(&x)); }
Terminal
$ rustc --edition 2021 trap_annotated_return.rs -o trap_annotated_return
error: lifetime may not live long enough
 --> trap_annotated_return.rs:1:71
  |
1 | fn main() { let x = String::from("hi"); let get = |s: &str| -> &str { s }; println!("{}", get(&x)); }
  |                                                       -        -      ^ returning this value requires that `'1` must outlive `'2`
  |                                                       |        |
  |                                                       |        let's call the lifetime of this reference `'2`
  |                                                       let's call the lifetime of this reference `'1`

error: aborting due to 1 previous error

The repair is to drop the parameter annotation - with the parameter's lifetime left to inference, the return annotation may stay or go, and the closure returns the parameter with the lifetimes tied. Dropping the return annotation alone does not repair it: the parameter annotation declares a fresh lifetime of its own, and returning the parameter across it fails the same way. An annotated value return, as in the eleventh family, is unaffected: the failure needs the returned type to be a reference, so that a lifetime exists to be declared fresh.

Checklist

  • The header checked: E0521 means an annotated closure parameter was stored in a place declared outside the closure - if the code is E0597, E0716, E0506, E0499, or E0106, or there is no code, the traps name the difference before any edit.
  • The labels read before editing: the diagnostic names the escaping parameter, calls it a reference valid only in the closure body, and names the outside declaration it escaped into - those two places are the whole problem.
  • The annotation accounted for: an annotated reference parameter declares a fresh lifetime, so any store of that parameter into a capture is suspect until the annotation is dropped or the stored value stops being the reference.
  • For a dropped annotation, the calls checked: inference ties the lifetimes, and a call whose argument dies before the container is read then fails as E0597 - the argument has to live as long as the stored reference is used.
  • For an owned store, the element type checked everywhere: the container, its readers, and any other writers all have to agree on the owned type the reference was replaced with.
  • For a named-lifetime repair, the tie checked: one lifetime name has to appear on both the container's elements and the parameter, or the declaration repeats the annotation's mistake in longer form.
  • The fixed program run, and its output checked against what the program was meant to print - several repairs compile in more than one form, and the one that preserves the behavior is the program's call, not the compiler's.

Sources

  • Rust, Error codes index: E0521 — for the definition of the error as borrowed data escaping outside a closure, for the Vec and annotated-parameter example, for a type annotation of a closure parameter implying a new lifetime declaration, and for dropping the annotation as the repair.
  • The Rust Programming Language, Closures: Capturing References or Moving Ownership — for closure type inference and annotation: parameter and return types are usually inferred, annotations are optional and add explicitness at the cost of verbosity, and closures are used in a narrow context rather than an exposed interface.
  • The Rust Reference, Closure expressions — for closures capturing their environment, preferring shared references and inferring mutable captures where the body needs them, and for each closure having its own unique anonymous type.
  • The Rust Reference, Lifetime elision — for the elision rules the error index points to, under which function and closure signatures acquire lifetimes that are not written.
  • Rust, Error codes index: E0597 — for the neighboring error where a borrow does not live long enough, against which the short-lived-argument trap is drawn.

Keep Exploring