How to Write a Closure in Rust
A closure in Rust is a function without a name that you can keep in a variable: let double = |n: i32| n * 2;, called as double(21). Its parameters go between two pipe characters, and unlike a function declared with fn, it can use the variables of the code around it.
Syntax
let <name> = |<parameter>: <type>| <expression>;
let <name> = |<parameter>: <type>| -> <return type> {
<code>
};
<name>(<argument>)
| Part | What it does |
|---|---|
|<parameter>: <type>| | The closure's parameters, between two pipe characters and separated by commas. The types are optional: without them, Rust works them out from how the closure is used. || means no parameters. |
<expression> | The body. Its value is what the closure returns. |
-> <return type> | Optional. When you write it, the body must be in braces. |
{ <code> } | A body of several lines. Its last expression, without a semicolon, is the value the closure returns. |
<name>(<argument>) | Calls the closure, like a function. |
The Rust Book, Closures: "Rust's closures are anonymous functions you can save in a variable or pass as arguments to other functions." And: "Unlike functions, closures can capture values from the scope in which they're defined."
The Example
The example writes three closures: double, which doubles a number; greet, whose body has several lines; and over_limit, which compares an amount with a limit variable defined outside it. Then a changed version leaves out the parameter's type and calls the closure with two kinds of number.
Prerequisites
- Rust, with Cargo. This guide uses Rust 1.100.1.
Step 1: Create the Project and Write the Code
cargo new demo
cd demo
cargo new demo creates a project with a src/main.rs. Replace its contents:

fn main() {
// A closure that takes a number and gives back twice that number.
let double = |n: i32| n * 2;
println!("{}", double(21));
// A closure whose body has several lines, inside braces.
let greet = |name: &str| {
let upper = name.to_uppercase();
format!("Hello, {upper}!")
};
println!("{}", greet("Ada"));
// A closure that uses a variable from the code around it.
let limit = 500;
let over_limit = |amount: i32| amount > limit;
println!("{}", over_limit(900));
println!("{}", over_limit(120));
}
|n: i32| n * 2takes ani32namednand returnsn * 2.|name: &str| { ... }has a body of several lines in braces. Its last line,format!("Hello, {upper}!"), has no semicolon, so it's the value the closure returns.|amount: i32| amount > limituseslimit, a variable ofmain, without taking it as a parameter.
Step 2: Run It
cargo run -q
42
Hello, ADA!
true
false
-q keeps Cargo quiet, so only the program's output shows. The command is the same in zsh, bash and PowerShell.
Step 3: Leave Out the Parameter's Type
Replace src/main.rs with a version whose closure has no parameter type, called first with a whole number and then with 2.5:
fn main() {
let double = |n| n * 2;
println!("{}", double(21));
println!("{}", double(2.5));
}
cargo run -q
error[E0308]: mismatched types
--> src/main.rs:4:27
|
4 | println!("{}", double(2.5));
| ------ ^^^ expected integer, found floating-point number
| |
| arguments to this function are incorrect
|
note: expected because the closure was earlier called with an argument of type `{integer}`
--> src/main.rs:3:27
|
3 | println!("{}", double(21));
| ------ ^^ expected because this argument is of type `{integer}`
| |
| in this closure call
note: closure parameter defined here
--> src/main.rs:2:19
|
2 | let double = |n| n * 2;
| ^
For more information about this error, try `rustc --explain E0308`.
error: could not compile `demo` (bin "demo") due to 1 previous error

What Happened
42isdouble(21).Hello, ADA!:greetturned the name into capitals and built the greeting.trueandfalse: 900 is over thelimitof 500, and 120 isn't. The closure usedlimitfrommain.- The changed version didn't compile. Without a type, Rust took the type of
nfrom the first call,double(21), which passes an integer, sodouble(2.5)didn't fit: "expected integer, found floating-point number". The note points at that first call. Give the parameter its type, as in|n: i32|, and pass values of that type.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Changing a variable of main from a closure that isn't mut, as in let add = || count += 1; | error[E0596]: cannot borrow `add` as mutable, as it is not declared as mutable | Declare it as let mut add: two calls then made count 2 |
An fn inside main that uses a variable of main | error[E0434]: can't capture dynamic environment in a fn item, with a help to use the closure form | Write a closure instead |
A return type without braces, as in |n: i32| -> i32 n * 2 | error: expected `{`, found `n`, because an "explicit return type requires closure body to be enclosed in braces" | Add braces: |n: i32| -> i32 { n * 2 } |
Calling with the wrong number of arguments, as in double(21, 2) | error[E0057]: this function takes 1 argument but 2 arguments were supplied | Pass one argument for each parameter |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
expected because the closure was earlier called with an argument of type `{integer}` | The closure has no parameter type, and two calls passed different types | Give the parameter its type, and pass values of that type |
error: expected `{`, found `n` on a closure | A return type with a body that isn't in braces | Put the body in braces |
FAQ
How do I pass a closure to a function?
Give the function a parameter of type impl Fn(<argument type>) -> <return type>. In my check, fn apply(value: i32, f: impl Fn(i32) -> i32) -> i32 with f(value) as its body returned 42 for apply(21, |n| n * 2) and 22 for apply(21, |n| n + 1).
Can a closure take no parameters?
Yes: let hello = || println!("hello"); printed hello when it was called as hello().
What's the difference between a closure and a function?
A function declared with fn can't use the local variables of the code around it: an fn inside main that read limit failed with E0434. A closure can, which is what made over_limit work.
Conclusion
|parameters| body writes a closure: a function without a name, kept in a variable or passed to another function. Give its parameters types when the first call shouldn't decide them, put a body of several lines in braces, and use the variables around it without passing them in.
Additional Resources
- Closures, in The Rust Programming Language.
- Closure expressions, in The Rust Reference.
