Rust
E0434 Can't Capture Environment Fix
A function written inside another function looks as if it should see the outer function's variables. It cannot. A nested fn item is a standalone function that happens to be declared in a small scope: it has its own parameters and its own locals, and nothing else. When its body names a variable from the enclosing function, the compiler stops with E0434, can't capture dynamic environment in a fn item, and suggests the closure form instead. Capturing is what closures do. A closure value carries the values it captured with it, the way a struct carries its fields. A function item carries nothing, which is also why it can be passed around as a plain function pointer. This guide shows the error in its common shapes, the two main repairs and when each one fits, and the nearby errors that share the scene but carry different codes.
Written November 27, 2026 · Tested with Rust 1.99.1 · 26 min read
- The error: a nested function using an enclosing local
- A value parameter of the enclosing function is the same case
- The type of the value changes nothing
- First fix: replace the nested function with a closure
Written November 27, 2026
Tested with Rust 1.99.1
What this guide is
E0434 is the error for a variable that comes from a dynamic environment being used inside a function item. Dynamic environment is the compiler's term for the local variables that happen to be alive around a piece of code: the locals and parameters of the function the code sits inside. A nested function can see three kinds of names in its body. It can see its own parameters and the locals it declares itself. It can see items, which are named things with a fixed place in the program, such as constants, statics, types, and other functions. And that is the whole list. The enclosing function's locals and value parameters are not on it, even though the nested function's text sits right below them. Generic parameters are a separate case: a nested function that uses the enclosing function's type or lifetime parameters fails with E0401, can't use generic parameters from outer item, and the fix is to declare the same generic parameter on the nested function itself.
The reason is what a function item is. A function item is a single fixed piece of code. Every call to it runs the same instructions, and the only values that can vary from call to call are the arguments passed in. There is nowhere in a function item to store a captured value, and no extra hidden argument that carries one. A closure is the opposite design. A closure expression builds a value, and that value holds the captured variables, borrowed or moved, for as long as the closure value lives. That is why the compiler's one suggestion for this error is to switch forms: the closure form exists for exactly the job the nested function was asked to do.
The sections below take the shapes in order. First the error itself, for a local, for a parameter, and for a value that does not implement Copy, to show that the type of the captured value changes nothing. Then the two main repairs, a closure and a parameter. Then the names a nested function can use, constants and statics, and the same error inside a method. Then what the restriction buys, a nested function used as a function pointer. Finally the three neighboring errors, and the exact rule with its sources.
The error: a nested function using an enclosing local
This program declares a local, declares a function below it, and has the function return the local:
fn main() {
let y = 5;
fn bar() -> u32 {
y
}
println!("{} {}", y, bar());
}
$ rustc --edition 2021 main.rs -o main.bin
error[E0434]: can't capture dynamic environment in a fn item
--> main.rs:4:9
|
4 | y
| ^
|
= help: use the `|| { ... }` closure form instead
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0434`.
The header names the code and the act: error[E0434], can't capture dynamic environment in a fn item. The span underlines the use of y inside bar, not the declaration of y and not the call in the print line. The one help line names the repair the compiler expects: use the || { ... } closure form instead. Nothing else in the program is wrong. The call bar() is fine as a call, and y is in scope as text, in the sense that the name is written inside the same function body. Scope as text is not what the nested function gets. Its body is a new item, and an item body starts with a clean set of value names: its parameters, its own locals, and items it can name by path.
Read the span placement once more, because it rules out a common first guess. The error is not about the order of declarations, and moving the function above the local or below it changes nothing. It is also not about the local being used twice, once in the print line and once in the function. The print line's use of y is ordinary code in the enclosing function and compiles on its own. Only the use inside the item is refused.
A value parameter of the enclosing function is the same case
The restriction covers parameters as well as locals declared with let. A parameter is a local that was filled in by the caller, and a nested function cannot capture it either:
fn outer(scale: u32) -> u32 {
fn inner() -> u32 {
scale
}
inner() + scale
}
fn main() {
println!("{}", outer(3));
}
$ rustc --edition 2021 main.rs -o main.bin
error[E0434]: can't capture dynamic environment in a fn item
--> main.rs:3:9
|
3 | scale
| ^^^^^
|
= help: use the `|| { ... }` closure form instead
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0434`.
The header, the help line, and the code are identical, and the span underlines scale inside inner. The use of scale in inner() + scale sits in the enclosing function and is not flagged. This shape matters because it is the one that arrives from refactoring. A helper that starts life as a few lines inside a function, reading the function's parameter directly, gets lifted into a nested function during cleanup, and the body still names the parameter. The lift changed the kind of thing the helper is, from inline code to an item, and items do not inherit the parameter list of the function they sit in. The helper needs the value handed to it, which is the second fix below, or it needs to be a closure, which is the first.
The type of the value changes nothing
It is natural to wonder whether a small value that implements Copy slips through, or whether a large value is the problem. Neither is true. The first example captured a u32, which implements Copy, and it failed. A String, which does not implement Copy, fails with the same code, the same header, and the same help line:
fn main() {
let name = String::from("veldica");
fn bar() -> usize {
name.len()
}
println!("{} {}", name.len(), bar());
}
$ rustc --edition 2021 main.rs -o main.bin
error[E0434]: can't capture dynamic environment in a fn item
--> main.rs:4:9
|
4 | name.len()
| ^^^^
|
= help: use the `|| { ... }` closure form instead
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0434`.
The span underlines name at the start of the method call, and that is the only difference in the output. There is no second error about moving, borrowing, or ownership, because the compiler refuses the capture before any of those questions arise. Copy status, size, and ownership all belong to the closure world, where captures actually happen and those questions have answers. In the function item world the capture itself is the error, so E0434 is always the first and only word on a nested function that names an enclosing local, whatever the local's type — unless the nested function also uses an enclosing generic parameter, which adds E0401 alongside it.
First fix: replace the nested function with a closure
The compiler's help line is the first fix. Delete the fn declaration and bind a closure to the same name. The closure captures the enclosing local, and the call site does not change, because a closure bound to a name is called with the same parentheses syntax as a function:
fn main() {
let y = 5;
let bar = || -> u32 { y };
println!("{}", bar());
}
$ rustc --edition 2021 main.rs -o main.bin
$ ./main.bin
5
The program prints 5 and exits with status 0. Two things changed and one thing did not. The declaration changed from an item to a value: bar is now a local variable holding a closure, declared at a point in the enclosing function's run, and it must be declared before it is called, where a nested function can be called from code written above it. The body kept the name y, and now the name works, because a closure body is allowed to name the locals around it and the closure value keeps what it captured. The call bar() is character-for-character what it was.
Choose this fix when the helper is used only inside this one function and its whole point is to work with the values that are already there. That is most nested functions in real code. The closure inherits the enclosing scope as its working material, needs no parameter list for the captured values, and can capture several of them at once. The costs are the ones that come with being a value. The closure has an anonymous type that cannot be written out as a name, it lives and dies with the scope that created it unless its captures are moved into it, and each closure expression in a program is its own distinct type. The next sections show the cases where those costs bite and the parameter fix or a move is the answer.
Second fix: keep the function, and pass the value in
When the helper needs to stay a function item, give it the value as a parameter and pass the value at the call. The nested function keeps its name, its item status, and its ability to be called from anywhere in the enclosing function. Its body names its own parameter, which is a name it is allowed to use:
fn main() {
let y = 5;
fn bar(y: u32) -> u32 {
y
}
println!("{}", bar(y));
}
$ rustc --edition 2021 main.rs -o main.bin
$ ./main.bin
5
The program prints 5 and exits with status 0. The parameter is named y here so the body stays the same line, but that is a choice, not a rule: the parameter can have any name, and the body uses the parameter's name. What makes this compile is not the spelling. It is that the value now arrives through the function's own front door, as an argument, which is the one channel a function item has for values that vary.
Choose this fix when the helper is called from several places with different values, when it is also used as a function pointer, or when making the data flow explicit is worth more than saving a parameter. A parameter is visible in the signature, so a reader can see what the helper needs without reading its body and guessing which enclosing names it touches. It also frees the helper to move. A function item with an honest parameter list can be lifted out of the enclosing function to module level later without its body changing at all, because it never depended on where it was declared. A closure that captures cannot be lifted that way. If there is any chance the helper will be promoted out of the function, the parameter form is the one that survives the move.
What a nested function can use: constants and statics
The ban is on the dynamic environment, not on every name from outside the item. Items are allowed, because an item is not part of any one call's environment. A constant has a fixed value baked into the program, and a static has a fixed place in memory, so a nested function can name both, including constants and statics declared inside the enclosing function itself:
fn main() {
const LIMIT: u32 = 5;
static LABEL: &str = "limit";
fn bar() -> u32 {
LIMIT
}
println!("{} {}", LABEL, bar());
}
$ rustc --edition 2021 main.rs -o main.bin
$ ./main.bin
limit 5
The program prints limit 5 and exits with status 0. bar reads LIMIT, a constant declared two lines above it in the same function body, and no error follows. This is the official error page's second suggested repair in working form: replace the captured variable with a constant or a static item. It fits when the value never actually varies, when the local was set once from a literal and read as if it were a fact about the program. If the value is computed from input, from a file, or from an earlier step of the run, it is a real local and this repair does not apply. Promoting a varying value to a constant to silence E0434 would change what the program computes, which is a redesign, not a fix. Note also what the constant form gives up: there is one LIMIT for the whole program, shared by every call, so per-call and per-value differences have nowhere to live.
The same error inside a method
Nesting inside a method changes nothing. A function declared inside a method body is still a function item, and the method's locals are still a dynamic environment it cannot capture:
struct Counter {
base: u32,
}
impl Counter {
fn total(&self) -> u32 {
let bonus = 3;
fn add_bonus() -> u32 {
bonus
}
self.base + bonus + add_bonus()
}
}
fn main() {
let c = Counter { base: 7 };
println!("{}", c.total());
}
$ rustc --edition 2021 main.rs -o main.bin
error[E0434]: can't capture dynamic environment in a fn item
--> main.rs:9:13
|
9 | bonus
| ^^^^^
|
= help: use the `|| { ... }` closure form instead
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0434`.
The span underlines bonus inside add_bonus, and the uses of bonus and self.base in the return line, which sit in the method itself, are not flagged. The repairs are the same two. Make add_bonus a closure and it captures bonus, or give it a parameter and pass bonus at the call. There is also a third option that methods make natural: put the helper on the type as its own method, and let it take the values it needs as parameters or read them from self. What does not exist is a form where the nested function quietly reads the method's locals or reaches the fields through self on its own. self is the method's parameter, and a parameter is exactly the kind of name this error is about.
Neighboring error: a field name is not a value at all
One method shape looks like E0434 and is not. If the nested function names a field of the struct, written bare, the field is not a local, not a parameter, and not an item. There is no value with that name in any scope the nested function can see, so the failure is a plain missing name:
struct Counter {
base: u32,
}
impl Counter {
fn total(&self) -> u32 {
fn add_base() -> u32 {
base
}
self.base + add_base()
}
}
fn main() {
let c = Counter { base: 7 };
println!("{}", c.total());
}
$ rustc --edition 2021 main.rs -o main.bin
error[E0425]: cannot find value `base` in this scope
--> main.rs:8:13
|
8 | base
| ^^^^ not found in this scope
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0425`.
The code is E0425: cannot find value base in this scope, with the label not found in this scope. Compare the two method programs line by line. They differ only in the name the nested function uses, bonus against base, and that difference decides the code. bonus exists as a value in the enclosing scope, so using it is a capture, and a capture in a function item is E0434. base exists only as a field, reached through a value such as self.base, so the bare name resolves to nothing at all, and a name that resolves to nothing is E0425. The distinction is useful in your own code because the repairs differ. E0434 is repaired by changing the helper's form or its inputs. This E0425 is repaired by giving the nested function the field's value as a parameter, or by passing self or the whole value in, so the name it needs exists in its own scope. Reading the label under the span tells you which situation you are in before you change anything: not found in this scope means the name is absent, and the E0434 header means the name is present and the capture is the problem.
What the restriction buys: a nested function is a function pointer
The ban on capture is also what makes a function item simple to pass around. A function that takes a fn() -> u32 parameter takes a plain function pointer: an address of code, with no data attached. A nested function can fill that parameter precisely because it carries no environment:
fn apply(f: fn() -> u32) -> u32 {
f()
}
fn main() {
fn bar() -> u32 {
42
}
println!("{}", apply(bar));
}
$ rustc --edition 2021 main.rs -o main.bin
$ ./main.bin
42
The program prints 42 and exits with status 0. bar is passed by name to apply, coerces to the function pointer type, and is called inside apply with nothing but its declared arguments, of which there are none. If bar could capture y from the first example, this call would need somewhere to keep y while apply runs, and a bare code address has no such place. A closure that captures cannot be passed where a fn pointer is required, for the same reason: the captured values are part of the closure, and the pointer type has no room for them. A closure that captures nothing can coerce to a function pointer, because there is nothing extra to carry. So the choice between the two fixes is also a choice about what the helper can later be used as. Keep it a function item with parameters, and it stays usable anywhere a function pointer is. Turn it into a capturing closure, and it is passed as a generic closure parameter or a trait object instead, which is fine in code written for closures and a type error in code written for function pointers.
After the closure fix: borrowing keeps the original usable
A closure captures in the lightest way that its body allows. A body that only reads a value captures it by shared reference, so the original value stays usable after the closure is created and called:
fn main() {
let name = String::from("veldica");
let bar = || name.len();
println!("{}", bar());
println!("{}", name.len());
}
$ rustc --edition 2021 main.rs -o main.bin
$ ./main.bin
7
7
The program prints 7 twice and exits with status 0. This is worth knowing because the value here is a String, the non-Copy type from the earlier section. In closure form it raises no ownership problem at all, because nothing was moved. The closure borrowed name, called a method that reads through a shared reference, and gave the borrow back by living no longer than the scope. The nested function version of this program failed with E0434 before ownership was ever considered. The closure version passes ownership without any extra work, because borrowing is the default capture for a body that only reads. Capture questions only get sharp when the closure has to outlive the scope, or when its body takes ownership of a value, which are the next two cases.
Neighboring error: using a value after a move closure takes it
Adding move to a closure forces every capture to be by value. For a value that does not implement Copy, that is a real move, and the original name is dead afterward. Code that goes on using the original name then fails, with a different code:
fn main() {
let name = String::from("veldica");
let bar = move || name.len();
println!("{}", bar());
println!("{}", name.len());
}
$ rustc --edition 2021 main.rs -o main.bin
error[E0382]: borrow of moved value: `name`
--> main.rs:5:20
|
2 | let name = String::from("veldica");
| ---- move occurs because `name` has type `String`, which does not implement the `Copy` trait
3 | let bar = move || name.len();
| ------- ---- variable moved due to use in closure
| |
| value moved into closure here
4 | println!("{}", bar());
5 | println!("{}", name.len());
| ^^^^ value borrowed here after move
|
help: consider cloning the value before moving it into the closure
|
3 ~ let value = name.clone();
4 ~ let bar = move || value.len();
|
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0382`.
The code is E0382: borrow of moved value. This error belongs to the repair, not to the original problem. The plain closure in the previous section needed no move, and adding one where it is not needed trades a working program for this error. The help block offers the standard way out when the move is genuinely needed and both users of the value are real: clone the value before the closure, move the clone in, and keep the original. The shorter way out, when the closure does not need to own anything, is to delete the move keyword and let the closure borrow. Reach for move only when the closure must own its captures, which is the case in the next section.
Neighboring error: a closure that outlives the value it borrows
The mirror problem arrives when a closure is asked to leave the scope where its captured value lives. Here a function builds a closure over its own local and tries to return the closure:
fn make() -> impl Fn() -> i32 {
let x = 5;
let f = || x;
f
}
fn main() {
println!("{}", make()());
}
$ rustc --edition 2021 main.rs -o main.bin
error[E0597]: `x` does not live long enough
--> main.rs:3:16
|
2 | let x = 5;
| - binding `x` declared here
3 | let f = || x;
| ---^
| | |
| | borrowed value does not live long enough
| value captured here
| assignment requires that `x` is borrowed for `'static`
4 | f
5 | }
| - `x` dropped here while still borrowed
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0597`.
The code is E0597: x does not live long enough. The closure captured x by reference, the reference would dangle the moment make returns and x is dropped, and the compiler refuses. This is the point where move earns its place. A move closure takes ownership of x, so the value travels with the closure and lives exactly as long as it:
fn make() -> impl Fn() -> i32 {
let x = 5;
let f = move || x;
f
}
fn main() {
println!("{}", make()());
}
$ rustc --edition 2021 main.rs -o main.bin
$ ./main.bin
5
The program prints 5 and exits with status 0. Set the three closure cases side by side and the pattern is plain. A closure used inside its own scope borrows and needs nothing extra. A closure returned out of its scope, or stored somewhere that outlives the scope, must own what it uses, and move is how it takes ownership. Sending a closure to a thread splits the same way: std::thread::spawn requires a 'static closure, so a borrowing one fails with E0373 and move is again the fix, while a scoped thread (std::thread::scope) may borrow the locals around it and needs neither. A move added without that need takes ownership anyway and can break later uses of the original name, which was the E0382 case. None of these three cases is E0434. E0434 is earlier and simpler: it is only about function items, which never capture at all, by borrow or by move.
The exact rule: a function item has no environment
The official page for E0434 states the rule in its first line: a variable used inside an inner function comes from a dynamic environment. Its erroneous example is the first shape in this guide: a function bar declared inside foo, returning the local y from foo. Its fixes are the two repairs this guide leads with, in the page's own order. The first replaces the function with a closure, keeping the body and the captured name. The second replaces the captured variable with a constant or a static item, so the name the inner function uses is an item rather than a local. The page does not list the parameter repair, which this guide verified separately: it follows from the same rule, because a parameter of the inner function is part of the inner function itself, not part of the environment around it.
The Reference's page on closure types explains the mechanism behind the first fix. A closure type is approximately a struct that contains the captured values, and the page lists the capture modes that decide how each value is held: an immutable borrow, a unique immutable borrow, a mutable borrow, or a move by value. That model explains every closure result in this guide. A reading body captures by immutable borrow, which is why the String stayed usable. A move closure forces the by-value mode, which is why the original name died. And a returned closure must hold its values in a form that survives the return, which is why the borrowing version failed with E0597 and the move version compiled. The Reference's page on functions gives the other half: a function is declared with the fn keyword, which defines the given name in the value namespace of the module or block where it is located, and when a function is referred to it yields a value of the corresponding function item type. A function item is a name for code. It is not a container, and the capture machinery described for closures has no counterpart for it.
The fixes, ranked
- First, replace the nested function with a closure when the helper lives and dies inside the enclosing function and works with the values that are already there. This is the compiler's own suggestion, it keeps the body and the call site as they are, and it handles several captured values at once with no signature changes.
- Second, keep the function item and pass each needed value in as a parameter when the helper is called with different values, is used as a function pointer, or may later be lifted to module level. The signature then states what the helper needs, and the body depends on nothing outside itself.
- Third, if the captured value never varies, declare it as a constant, or as a static when it needs a fixed address, and let the nested function name the item. Check first that the value really is fixed for the whole program, because this repair gives every call the same value.
- Fourth, inside a method, consider making the helper a method of the type, taking what it needs as parameters or reading it from
self. The nested function form has no access toself, so a helper that mostly works on the type's fields usually belongs on the type. - Before choosing any of these, confirm the code really is E0434. A bare field name in a nested function is E0425 and needs the value brought into scope. A value used after a move closure took it is E0382 and needs a clone or a dropped
move. A closure returned past its captured value's life is E0597 and needsmove, which is the one case where adding the keyword is the fix rather than the cause.
Which fix for which cause
- Nested function names a local of the enclosing function: E0434, can't capture dynamic environment in a fn item. Use a closure, or pass the local in as a parameter.
- Nested function names a value parameter of the enclosing function: E0434, same header and help. The value parameter is part of the dynamic environment too. Use a closure, or give the nested function its own parameter and pass the value at the call.
- Nested function names a local inside a method: E0434, same header and help. Use a closure, pass the value in, or move the helper onto the type as a method.
- Nested function names a constant or a static, including one declared inside the enclosing function: no error. Items are outside the dynamic environment and are always nameable.
- Nested function names a field of the enclosing type, written bare: E0425, cannot find value in this scope. The field is not a value name. Pass the field's value, or
self, into the nested function, or make the helper a method. - A closure captures a value by shared reference and the original is used later in the same scope: no error. Reading captures borrow, and the original stays usable.
- A move closure takes a non-Copy value and the original name is used afterward: E0382, borrow of moved value. Clone the value before the closure, or drop
moveif the closure does not need to own the value. - A closure that borrows a local is returned or stored past the scope: E0597, the value does not live long enough. Add
moveso the closure owns the value, or return the value itself instead of a closure over it. - A borrowing closure passed to
std::thread::spawn: E0373, closure may outlive the current function. Addmove; insidestd::thread::scopea borrowing closure is allowed as it stands.
Checklist
- Read the name under the span before changing anything. If the name is a local or a value parameter of the enclosing function, the code is E0434 and the fix is about the helper's form. If the label says the name was not found in this scope, the name does not exist as a value at all, and bringing it into scope is the fix.
- Do not check the captured value's type for a clue. Copy and non-Copy values fail identically under E0434, because the capture itself is refused before ownership is considered.
- Decide whether the helper needs to stay a function item. If it is passed as a
fnpointer, called before its declaration point, or headed for module level, keep the item and use parameters. Otherwise the closure is the shorter path. - Count what the closure version needs. A closure used in its own scope should borrow by default. Add
moveonly when the closure leaves the scope, and expect any later use of a moved non-Copy original to fail with E0382. - If a value looks like a constant, verify that it never varies before promoting it. A constant or static repair is exact only for values that are fixed for the whole run of the program.
- After the fix, run the program, not just the compiler. The fixed programs in this guide print the value the helper was trying to reach, and that output line is the proof the value now arrives by a channel the compiler allows.
Related guides on this site
- E0401 Can't Use Generic Parameters Fix
- E0463 Can't Find Crate Fix
- E0604 Only u8 Cast as Char Fix
- Fix Rust E0597 "`x` does not live long enough" — a Block Scope, a Stored Reference, a Struct Field, and a Closure Capture
Sources
- Rust Compiler Error Index, E0434 — for a variable used inside an inner function coming from a dynamic environment, for the erroneous example of an inner function returning an enclosing local, for replacing the function with a closure as a fix, and for replacing the captured variable with a constant or a static item as the other fix.
- The Rust Reference, Closure types — for a closure type being approximately a struct that contains the captured values, and for the capture modes of immutable borrow, unique immutable borrow, mutable borrow, and move by value.
- The Rust Reference, Functions — for a function being declared with the
fnkeyword and defining its name in the value namespace of the module or block where it is located, and for a referred function yielding a value of the corresponding function item type.
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.