Module 10 · Closures & iterators
10.1Closures & Fn, FnMut, FnOnce
How closures capture variables by borrow or by value, what the Fn, FnMut and FnOnce traits say about a closure, and how to pass closures to functions and return them.
On this page
Concept map
| Concept | TypeScript | C# | Rust |
|---|---|---|---|
| An inline function | (score) => score * 2 | score => score * 2 | |score| score * 2 |
| Using an outer variable inside it | The function sees the variable itself, including later changes | The variable becomes a field of a hidden heap object that every lambda using it shares | Borrowed with & or &mut, or moved in, depending on what the body does |
| Keeping captured values after the scope ends | Automatic; the garbage collector keeps them alive | Automatic; the closure object keeps them alive | move |...| makes the closure own what it captures |
| Type of a function value | (score: number) => number | Func<int, int>, Action<string> | impl Fn(i32) -> i32, &dyn Fn(i32) -> i32, Box<dyn Fn(i32) -> i32> |
| What the function may do with its captures | Anything, as often as it's called | Anything, as often as it's called | Fn reads, FnMut changes, FnOnce uses them up (call once) |
Rust closures look and feel like arrow functionslambdas: a short inline function that can use variables from the code around it. The difference is in how they use those variables. A TypeScript arrow function holds on to the variables themselves, and the garbage collector keeps them alive for as long as the function exists.A C# lambda turns the variables it uses into fields of a hidden object on the heap, and the garbage collector keeps that object alive for as long as the lambda exists. Rust has no garbage collector, so each closure borrows or takes ownership of what it uses, and the borrow checker treats those captures like any other borrow. This lesson shows how a closure captures, what move changes, what the three traits Fn, FnMut and FnOnce mean, and how to pass closures around.
Closures are inline functions
A closure’s parameters go between two pipes, |score|, and its body follows. A one-expression body needs no braces; a longer one is a block, whose last expression is the result.
const bonus = 10;
const addBonus = (score: number): number => score + bonus;
const double = (score: number) => score * 2;
const describe = (score: number) => {
const label = score >= 50 ? "pass" : "fail";
return `${score}: ${label}`;
};
console.log(addBonus(45));
console.log(double(addBonus(1)));
console.log(describe(addBonus(45)));var bonus = 10;
Func<int, int> addBonus = score => score + bonus;
Func<int, int> twice = score => score * 2;
Func<int, string> describe = score =>
{
var label = score >= 50 ? "pass" : "fail";
return $"{score}: {label}";
};
Console.WriteLine(addBonus(45));
Console.WriteLine(twice(addBonus(1)));
Console.WriteLine(describe(addBonus(45)));let bonus = 10;
let add_bonus = |score: i32| -> i32 { score + bonus };
let double = |score| score * 2;
let describe = |score| {
let label = if score >= 50 { "pass" } else { "fail" };
format!("{score}: {label}")
};
println!("{}", add_bonus(45));
println!("{}", double(add_bonus(1)));
println!("{}", describe(add_bonus(45)));Output
55 22 55: pass
- Types are optional.
add_bonusspells them out;doubleanddescribelet the compiler infer them from the first call. Unlike afn, a closure can usually leave its parameter and return types out. ||is an empty parameter list. A closure that takes nothing is written|| println!("hi"). In that position||isn’t the logical OR operator.- Only closures capture. A nested
fninsidemainis an ordinary function: it can’t usemain’s local variables, and the compiler rejects it withE0434(“can’t capture dynamic environment in a fn item”). When you need a local, use a closure.
The C# version names its second lambda twice because a local double would clash with the double type keyword. Rust has no such clash: its floating-point type is f64.
How a closure captures
TypeScriptC# never asks how a function holds on to an outer variable. Rust does, and it picks the answer from what the closure’s body does with each variable, choosing the weakest form that works:
| The body… | The closure captures | Like writing |
|---|---|---|
| only reads the variable | a shared borrow | &count |
| changes the variable | a mutable borrow | &mut count |
| moves the value out: returns it, drops it, or passes it on by value | the value itself | count (a move) |
Using a Copy value such as an i32 only reads it, so a closure borrows it rather than taking it (unless you write move, below). Here’s a closure that changes an outer counter:
let count = 0;
const increment = () => {
count += 1;
};
increment();
increment();
console.log(count);var count = 0;
Action increment = () => count++;
increment();
increment();
Console.WriteLine(count);let mut count = 0;
let mut increment = || count += 1;
increment();
increment();
println!("{count}");Output
2
increment changes count, so it captures &mut count. Two muts appear: let mut count because the value changes, and let mut increment because calling the closure changes the state it carries (its mutable borrow). Forget the second one and the compiler stops you with E0596.
Because the capture is a real &mut borrow, the usual rule applies: while the closure is still going to be used, nothing else may touch count. Reading count between two calls doesn’t compile:
let mut count = 0;
let mut increment = || count += 1;
increment();
println!("{count}");
increment();Rust doesn't compile this: error E0502
error[E0502]: cannot borrow `count` as immutable because it is also borrowed as mutable
--> main.rs:4:12
|
2 | let mut increment = || count += 1;
| -- ----- first borrow occurs due to use of `count` in closure
| |
| mutable borrow occurs here
3 | increment();
4 | println!("{count}");
| ^^^^^ immutable borrow occurs here
5 | increment();
| --------- mutable borrow later used here
|
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)| Line | Code | countowner | increment (&mut count)mutable borrow (&mut) | &countshared borrow (&) | What happens |
|---|---|---|---|---|---|
| 1 | let mut count = 0; | ownscount starts | |||
| 2 | let mut increment = || count += 1; | count alive | &mutincrement (&mut count) starts | The closure borrows count mutably | |
| 3 | increment(); | count alive | increment (&mut count) alive | ||
| 4 | println!("{count}"); | count alive | increment (&mut count) alive | &&count starts | errorE0502: println! reads count, but increment still holds &mut count |
| 5 | increment(); | count ends | increment (&mut count) ends | Last use of increment: the borrow ends here |
A timeline of the five lines above. count owns the number from line 1 to line 5. The closure increment captures a mutable borrow of count on line 2 and keeps it until its last call on line 5. Line 4 needs a shared borrow of count to print it while the mutable borrow is still alive, so the compiler rejects line 4 with E0502.
The borrow lasts from where the closure is created to its last call, not to the end of the block. Move the println! below the last increment() and it compiles, which is what the counter.rs example above does. In TypeScript, the arrow function and the surrounding code share count freely, and either can change it at any time.In C#, the lambda and the method share count through the hidden closure object, and either can change it at any time. Rust allows only one writer at a time, so a closure can’t change a value behind your back while you’re reading it.
The loop-variable trap
That rule also rules out a classic closure bug. In TypeScript, closures created in a var loop all share one i:In C#, lambdas created in a for loop all share one i:
const callbacks: (() => number)[] = [];
for (var i = 0; i < 3; i++) {
callbacks.push(() => i);
}
console.log(callbacks.map((callback) => callback()).join(" "));Output
3 3 3
Each arrow function reads i when it’s called, after the loop has finished. Writing let i fixes it, because let creates a fresh binding for each pass of the loop.
var callbacks = new List<Func<int>>();
for (var i = 0; i < 3; i++)
{
callbacks.Add(() => i);
}
Console.WriteLine(string.Join(" ", callbacks.Select(callback => callback())));Output
3 3 3
All three lambdas capture the same i, which lives in one hidden closure object, and they read it after the loop has finished. A foreach variable is fresh for each pass (since C# 5), so foreach (var i in Enumerable.Range(0, 3)) prints 0 1 2; with for, you copy i into a local inside the loop.
In Rust, the same mistake doesn’t compile. If closures borrow a counter that the loop keeps changing, the change conflicts with the borrows:
let mut callbacks = Vec::new();
let mut i = 0;
while i < 3 {
callbacks.push(|| i);
i += 1;
}Rust doesn't compile this: error E0506
error[E0506]: cannot assign to `i` because it is borrowed --> main.rs:5:5 | 4 | callbacks.push(|| i); | --------- -- - borrow occurs due to use in closure | | | | | `i` is borrowed here | borrow later used here 5 | i += 1; | ^^^^^^ `i` is assigned to here but it was already borrowed
And with a for loop over a range, each pass has its own i that only lives for that pass, so a closure that only borrowed it couldn’t be stored for later (E0597). The fix is the next section’s keyword, move, which copies each i into its closure:
let mut callbacks = Vec::new();
for i in 0..3 {
callbacks.push(move || i);
}
let results: Vec<i32> = callbacks.iter().map(|callback| callback()).collect();
println!("{results:?}");Output
[0, 1, 2]
move closures own what they capture
Sometimes a closure has to outlive the variables it uses: you return it from a function, store it in a struct, or hand it to a thread. A borrow can’t outlive its value, so the closure must own its captures instead. Writing move before the parameters makes it capture everything it uses by value.
function makeGreeter(greeting: string): (name: string) => string {
return (name) => `${greeting}, ${name}!`;
}
const hello = makeGreeter("Hello");
console.log(hello("Ada"));
console.log(hello("Grace"));var hello = MakeGreeter("Hello");
Console.WriteLine(hello("Ada"));
Console.WriteLine(hello("Grace"));
static Func<string, string> MakeGreeter(string greeting) => name => $"{greeting}, {name}!";fn make_greeter(greeting: String) -> impl Fn(&str) -> String {
move |name| format!("{greeting}, {name}!")
}
fn main() {
let hello = make_greeter(String::from("Hello"));
println!("{}", hello("Ada"));
println!("{}", hello("Grace"));
}Output
Hello, Ada! Hello, Grace!
The return type impl Fn(&str) -> String means “some closure that takes a &str and returns a String”. Every closure has its own unnamed type, so you can’t write it out; impl Fn says what it can do instead.
Without move, the closure would only borrow greeting, a local variable of make_greeter that’s dropped when the function returns. The compiler catches it and suggests the fix:
fn make_greeter(greeting: String) -> impl Fn(&str) -> String {
|name| format!("{greeting}, {name}!")
}Rust doesn't compile this: error E0373
error[E0373]: closure may outlive the current function, but it borrows `greeting`, which is owned by the current function
--> main.rs:2:5
|
2 | |name| format!("{greeting}, {name}!")
| ^^^^^^ -------- `greeting` is borrowed here
| |
| may outlive borrowed value `greeting`
|
note: closure is returned here
--> main.rs:2:5
|
2 | |name| format!("{greeting}, {name}!")
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: to force the closure to take ownership of `greeting` (and any other referenced variables), use the `move` keyword
|
2 | move |name| format!("{greeting}, {name}!")
| ++++Mental model shiftmove decides how, not what
move changes how a closure captures (by value instead of by borrow). It doesn’t change what the closure may do with its captures. make_greeter’s closure owns greeting but only reads it, so you can call it as often as you like. For a Copy value such as an i32, move copies it, and the original stays usable. For a String or a Vec, move moves it, so the code outside can’t use it afterwards. Clone it first if you need both: let greeting_for_closure = greeting.clone();.
Fn, FnMut and FnOnce
TypeScriptC# has one kind of function value, and any of them can read, change or hand off what it captured, as often as it’s called. Rust sorts closures by what their body does with their captures, using three traits:
| Trait | The closure’s body… | How you can call it |
|---|---|---|
Fn | only reads its captures, or captures nothing | Any number of times, even from several places at once. It only needs a shared borrow of the closure. |
FnMut | changes a capture | Any number of times, one call at a time. It needs a mutable borrow of the closure, so the variable holding it must be let mut. |
FnOnce | moves a capture out: returns it, drops it, or passes it on by value | Once. The call uses the closure up. |
You never write these on a closure: the compiler works out which ones it implements from the body. Here’s one of each:
const greeting = "Hello";
const greet = (name: string) => `${greeting}, ${name}!`;
console.log(greet("Ada"));
const names: string[] = [];
const remember = (name: string) => {
names.push(name);
};
remember("Ada");
remember("Grace");
console.log(names.join(", "));
const finish = () => names;
const all = finish();
console.log(`${all.length} names`);var greeting = "Hello";
Func<string, string> greet = name => $"{greeting}, {name}!";
Console.WriteLine(greet("Ada"));
var names = new List<string>();
Action<string> remember = name => names.Add(name);
remember("Ada");
remember("Grace");
Console.WriteLine(string.Join(", ", names));
Func<List<string>> finish = () => names;
var all = finish();
Console.WriteLine($"{all.Count} names");let greeting = String::from("Hello");
let greet = |name: &str| format!("{greeting}, {name}!"); // Fn: only reads
println!("{}", greet("Ada"));
let mut names = Vec::new();
let mut remember = |name: &str| names.push(name.to_string()); // FnMut: changes names
remember("Ada");
remember("Grace");
println!("{}", names.join(", "));
let finish = move || names; // FnOnce: hands names to the caller
let all = finish();
println!("{} names", all.len());Output
Hello, Ada! Ada, Grace 2 names
finish returns the Vec it captured, so after one call it no longer has it. Calling it a second time is a compile error: E0382, “use of moved value: finish”, with the note “closure cannot be invoked more than once because it moves the variable names out of its environment”.
The traits nest. Every closure implements FnOnce, since anything can be called once. A closure that implements Fn also implements FnMut, since read-only is a special case of “may change”. So a function that accepts FnOnce takes any closure, and one that accepts Fn takes the fewest. The function’s bound decides what callers may pass:
fn call_twice<F: FnMut()>(mut action: F) {
action();
action();
}
fn main() {
let name = String::from("Ada");
call_twice(|| println!("Hi, {name}")); // Fn closures are FnMut too
let mut count = 0;
call_twice(|| count += 1);
println!("{count}");
}Output
Hi, Ada Hi, Ada 2
A closure that can run only once is rejected, because call_twice calls it twice:
fn call_twice<F: FnMut()>(mut action: F) {
action();
action();
}
fn main() {
let report = String::from("done");
let send = move || drop(report);
call_twice(send);
}Rust doesn't compile this: error E0525
error[E0525]: expected a closure that implements the `FnMut` trait, but this closure only implements `FnOnce`
--> main.rs:8:16
|
8 | let send = move || drop(report);
| ^^^^^^^ ------ closure is `FnOnce` because it moves the variable `report` out of its environment
| |
| this closure implements `FnOnce`, not `FnMut`
9 | call_twice(send);
| ---------- ---- the requirement to implement `FnMut` derives from here
| |
| required by a bound introduced by this call
|
note: required by a bound in `call_twice`
--> main.rs:1:18
|
1 | fn call_twice<F: FnMut()>(mut action: F) {
| ^^^^^^^ required by this bound in `call_twice`TypeScriptC# can’t express this. A callback that must only run once, like a “resolve” or a “dispose”, has to guard itself with a flag at run time. In Rust, FnOnce makes the second call a compile error.
Passing and returning closures
A function that takes a closure can spell the parameter type in several ways. Here are four, and the first three accept the same closures:
fn apply_impl(score: i32, rule: impl Fn(i32) -> i32) -> i32 {
rule(score)
}
fn apply_generic<F>(score: i32, rule: F) -> i32
where
F: Fn(i32) -> i32,
{
rule(score)
}
fn apply_dyn(score: i32, rule: &dyn Fn(i32) -> i32) -> i32 {
rule(score)
}
fn apply_pointer(score: i32, rule: fn(i32) -> i32) -> i32 {
rule(score)
}
fn main() {
let bonus = 5;
let add_bonus = |score| score + bonus;
println!("{}", apply_impl(10, add_bonus));
println!("{}", apply_generic(10, add_bonus));
println!("{}", apply_dyn(10, &add_bonus));
println!("{}", apply_pointer(10, |score| score * 2)); // captures nothing
}Output
15 15 15 20
impl Fn(i32) -> i32andF: Fn(i32) -> i32are the same thing written two ways: a generic function. The compiler makes a separate copy of the function for each closure type it’s called with, so the call is direct and usually inlined. Use the namedFwhen you need it twice, in awhereclause, or in a struct field.&dyn Fn(i32) -> i32borrows a closure of any type through one compiled function. Each call goes through a pointer, like a virtual method call. No allocation.fn(i32) -> i32is a plain function pointer. It accepts named functions and closures that capture nothing, and nothing else. It’s the closest match to astaticlambda.
All four use Fn to keep the comparison simple. The same spellings work with the other two traits, such as impl FnMut(i32) -> i32 or &mut dyn FnMut(i32) -> i32; the flow under “Which one should I use?” below shows which trait to ask for.
(add_bonus can be passed three times because it only holds a &i32, and a closure whose captures are all Copy is Copy too.) impl Trait vs dyn Trait explains the trade-off between the generic and dyn forms in general.
One more spelling, Box<dyn Fn(i32) -> i32>, owns its closure on the heap. You need it when one variable or collection must hold closures of different types, since every closure has its own type, even two with the same body:
const bonus = 5;
const rules: ((score: number) => number)[] = [
(score) => score * 2,
(score) => score + bonus,
(score) => Math.min(score, 100),
];
let score = 48;
for (const rule of rules) {
score = rule(score);
}
console.log(score);var bonus = 5;
List<Func<int, int>> rules =
[
score => score * 2,
score => score + bonus,
score => Math.Min(score, 100),
];
var score = 48;
foreach (var rule in rules)
{
score = rule(score);
}
Console.WriteLine(score);let bonus = 5;
let rules: Vec<Box<dyn Fn(i32) -> i32>> = vec![
Box::new(|score| score * 2),
Box::new(move |score| score + bonus),
Box::new(|score| score.min(100)),
];
let mut score = 48;
for rule in &rules {
score = rule(score);
}
println!("{score}");Output
100
A TypeScript function type like (score: number) => number covers every function with that shape, so the array needs nothing special.A C# delegate type like Func<int, int> covers every lambda with that shape, so the list needs nothing special. In Rust, Box<dyn Fn(i32) -> i32> plays that role: one type, whatever closure is inside.
Returning a closure follows the same split. Return impl Fn(...) when the function always returns the same closure, like make_greeter. Return Box<dyn Fn(...)> when it picks one of several:
fn make_rule(kind: &str, amount: i32) -> Box<dyn Fn(i32) -> i32> {
if kind == "double" {
Box::new(move |score| score * amount)
} else {
Box::new(move |score| score + amount)
}
}
fn main() {
let rule = make_rule("bonus", 5);
println!("{}", rule(10));
}Output
15
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
A plain closure |x| ... | The closure is used while its captured variables are still in scope: passed to map, sort_by_key, a callback you call right away. The default. | It borrows what it needs, so nothing is copied or moved, and you keep using your variables afterwards. | let add_bonus = |score| score + bonus; |
move |x| ... | The closure outlives the current scope: you return it, store it, or send it to a thread. | It owns its captures, so it can’t hold a dangling borrow. | move |name| format!("{greeting}, {name}!"). Clone first to keep your own copy. |
impl Fn(A) -> B parameter (or impl FnMut, impl FnOnce) | A function takes a closure and calls it. The default parameter type. | A direct call for each closure type, usually inlined: no allocation, no pointer chasing. | fn apply(score: i32, rule: impl Fn(i32) -> i32). Pick the trait with the flow below. |
F: Fn(A) -> B generic | Same as impl Fn, but you need to name the type: twice in a signature, in a where clause, or in a struct field. | Identical code to impl Fn; the name is the only difference. | fn apply<F: Fn(i32) -> i32>(rule: F) or struct Button<F: Fn()> { on_click: F }. |
&dyn Fn(A) -> B | You only borrow the closure, and you want one compiled copy of the function, for example because it’s large and called with many closures. | No allocation, and the function is compiled once. Each call is an indirect call. | fn apply(rule: &dyn Fn(i32) -> i32); call apply(&add_bonus). |
Box<dyn Fn(A) -> B> | You store closures of different types together (a Vec, a map, a struct field), or return one of several closures. | One owned type for any closure with that signature. Costs a heap allocation per closure. | Vec<Box<dyn Fn(i32) -> i32>>; Box::new(move |score| score + amount). |
fn(A) -> B | You take a named function or a closure that captures nothing: lookup tables of functions, plain callbacks. | A single pointer, no generics, and it’s Copy. | fn apply(score: i32, rule: fn(i32) -> i32); call apply(10, i32::abs). |
impl Fn(A) -> B return type | A function builds and returns one closure. | No allocation, and the caller can’t depend on the closure’s type. | fn make_greeter(greeting: String) -> impl Fn(&str) -> String, returning a move closure. |
Rule of thumb: write a plain closure, and add move only when the compiler says it may outlive what it borrows (E0373, E0597). To accept a closure, take impl ... and pick the trait by how you call it: FnOnce if you call it once, FnMut if you call it several times, and Fn only if you call it through a shared reference. Reach for &dyn Fn and Box<dyn Fn> only when you need one type for many closures.
Choosing the trait for a parameter is a question about how your function calls the closure. Ask in order; the first “yes” gives the bound:
Do you call it at most once?
YesNoAccept
FnOnceThe loosest bound: every closure qualifies, including ones that move a captured value out. Typical for a callback that runs on completion or a fallback that computes a default.Do you call it through a shared reference: from a method that takes
&self, through&dyn, or from several threads at once?YesNoAccept
FnOnly closures that read their captures qualify, so calling them while they are shared is safe.Otherwise: Accept
FnMut: you call it several times, one call at a time, and callers may pass closures that update a counter or push to a list. Take it asmut action: impl FnMut().
This is also how the standard library chooses: Option::map calls its closure at most once and takes FnOnce, Iterator::map calls it once per item and takes FnMut, and std::thread::spawn runs it once on another thread and takes FnOnce.
Under the hood
A closure is a struct the compiler writes for you. Its fields are the captures, and calling it calls a method on that struct. let mut increment = || count += 1; becomes roughly this:
struct IncrementClosure<'a> {
count: &'a mut i32,
}
impl IncrementClosure<'_> {
fn call_mut(&mut self) {
*self.count += 1;
}
}
fn main() {
let mut count = 0;
let mut increment = IncrementClosure { count: &mut count };
increment.call_mut();
increment.call_mut();
println!("{count}");
}The struct holds a &mut i32, which is why the borrow checker treats the closure exactly like that borrow, and its method takes &mut self, which is why the variable must be let mut and why the closure is FnMut. (The 'a says the struct can’t outlive count; Module 11 covers that syntax.) A move closure holds the values themselves, and an FnOnce closure’s method takes self, consuming the struct.
So a closure is only as big as its captures, and it lives on the stack like any other value:
let count = 5;
let name = String::from("Ada");
let nothing = || 1;
let reads = || count + 1;
let owns = move || name.len();
println!("nothing: {}", size_of_val(¬hing));
println!("reads: {}", size_of_val(&reads));
println!("owns: {}", size_of_val(&owns));
let boxed: Box<dyn Fn() -> usize> = Box::new(owns);
println!("boxed: {}", size_of_val(&boxed));Output
nothing: 0 reads: 8 owns: 24 boxed: 16
Today, on a 64-bit target, a closure that captures nothing takes 0 bytes, one that borrows count holds an 8-byte pointer, and one that owns a String holds the 24-byte String itself. A Box<dyn Fn> is 16 bytes: a pointer to the closure on the heap and a pointer to a table of its methods (its vtable).
In TypeScript, every function value is an object on the heap, and the engine keeps the captured variables in a heap-allocated environment that the function points to. That’s why an arrow function sees later changes to the variable: it reads the shared environment each time.
In C#, the compiler moves every captured local into a generated class (often called a display class), normally allocates it on the heap, and creates a delegate object pointing at a method on it. That’s why lambdas in one scope share a variable, and why a lambda can outlive the method that made it. Calling a delegate is an indirect call unless the JIT can see through it.
Rust closures passed as impl Fn or F: Fn need no heap and no indirect call: the compiler knows the closure’s exact type, generates code for it, and can inline the body at the call site. That’s why iterator chains full of closures compile to plain loops, as the next lesson shows.
One more detail: closures capture the exact fields they use, not the whole variable. A closure that reads player.name borrows only that field, so you can change player.score while it’s alive:
struct Player {
name: String,
score: u32,
}
fn main() {
let mut player = Player {
name: String::from("Ada"),
score: 0,
};
let greet = || println!("Hi, {}", player.name); // borrows player.name only
player.score += 10; // fine: a different field
greet();
println!("{}", player.score);
}Output
Hi, Ada 10
Common pitfalls
Common pitfallEvery closure has its own type
Two closures never have the same type, even with identical signatures. So an if that returns one of two capturing closures doesn’t fit a single impl Fn return type:
fn make_rule(kind: &str, amount: i32) -> impl Fn(i32) -> i32 {
if kind == "double" {
move |score| score * amount
} else {
move |score| score + amount
}
}Rust doesn't compile this: error E0308
error[E0308]: `if` and `else` have incompatible types
--> main.rs:5:9
|
2 | / if kind == "double" {
3 | | move |score| score * amount
| | ---------------------------
| | |
| | the expected closure
| | expected because of this
4 | | } else {
5 | | move |score| score + amount
| | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected closure, found a different closure
6 | | }
| |_________- `if` and `else` have incompatible types
|
= note: expected closure `{closure@main.rs:3:9: 3:21}`
found closure `{closure@main.rs:5:9: 5:21}`
= note: no two closures, even if identical, have the same type
= help: consider boxing your closure and/or using it as a trait object
help: you could change the return type to be a boxed trait object
|
1 - fn make_rule(kind: &str, amount: i32) -> impl Fn(i32) -> i32 {
1 + fn make_rule(kind: &str, amount: i32) -> Box<dyn Fn(i32) -> i32> {
|
help: if you change the return type to expect trait objects, box the returned expressions
|
3 ~ Box::new(move |score| score * amount)
4 | } else {
5 ~ Box::new(move |score| score + amount)
|impl Fn means “one specific type the caller doesn’t see”, and there are two here. Return Box<dyn Fn(i32) -> i32> and box each branch, as in make_rule above. The same applies to a Vec of closures: vec![|score| score * 2, |score| score + 1] doesn’t compile, while Vec<Box<dyn Fn(i32) -> i32>> does. (Closures that capture nothing are an exception: they can be turned into the same fn pointer type.)
Common pitfallA closure's types are fixed by its first use
let double = |score| score * 2; has no generic type parameter. The compiler infers one concrete type from the first call, so calling it with an i32 and then with an f64 is a type mismatch (E0308). If you need one function for several types, write a generic fn.
Common pitfallmove moves your String too
A move closure that uses a String takes it, and the code after it can’t use the variable anymore:
let name = String::from("Ada");
let greet = move || println!("Hi, {name}");
greet();
println!("{name}");Rust doesn't compile this: error E0382
error[E0382]: borrow of moved value: `name`
--> main.rs:4:12
|
1 | let name = String::from("Ada");
| ---- move occurs because `name` has type `String`, which does not implement the `Copy` trait
2 | let greet = move || println!("Hi, {name}");
| ------- ---- variable moved due to use in closure
| |
| value moved into closure here
3 | greet();
4 | println!("{name}");
| ^^^^ value borrowed here after move
|
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider cloning the value before moving it into the closure
|
2 ~ let value = name.clone();
3 ~ let greet = move || println!("Hi, {value}");
|Clone first and move the clone (let name_for_greet = name.clone();), or drop move if the closure doesn’t outlive name.
Common pitfallAn FnMut closure needs let mut
A closure that changes a capture changes its own state when you call it, so the variable that holds it must be mutable: let mut increment = || count += 1;. Without mut, calling it fails with E0596 (“cannot borrow increment as mutable”). The same goes for an impl FnMut parameter: write mut action: impl FnMut().
Try it yourself
Exercise: port this to Rust
Port this counter factory to Rust. Each counter keeps its own count, and step sets how much it goes up by.
function makeCounter(step: number): () => number {
let count = 0;
return () => {
count += step;
return count;
};
}
const first = makeCounter(1);
const second = makeCounter(10);
console.log(first());
console.log(first());
console.log(second());var first = MakeCounter(1);
var second = MakeCounter(10);
Console.WriteLine(first());
Console.WriteLine(first());
Console.WriteLine(second());
static Func<int> MakeCounter(int step)
{
var count = 0;
return () =>
{
count += step;
return count;
};
}Expected output
1 2 10
Show a hint
The counter must outlive make_counter, so the returned closure needs move. It changes its count on every call, so the return type is impl FnMut() -> i32, and the variables holding the counters must be let mut.
Show a solution
fn make_counter(step: i32) -> impl FnMut() -> i32 {
let mut count = 0;
move || {
count += step;
count
}
}
fn main() {
let mut first = make_counter(1);
let mut second = make_counter(10);
println!("{}", first());
println!("{}", first());
println!("{}", second());
}move copies count and step into the closure, so each counter owns its own state and nothing borrows a local of make_counter after it returns. Because the closure changes count, it's FnMut, which is why main declares first and second with let mut. No heap allocation is needed: impl FnMut returns the closure's hidden struct by value.
Saved in this browser only.