Skip to main content

How to Write a Closure in Rust

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
let <name> = |<parameter>: <type>| <expression>;
let <name> = |<parameter>: <type>| -> <return type> {
<code>
};

<name>(<argument>)
PartWhat 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​

Terminal
cargo new demo
cd demo

cargo new demo creates a project with a src/main.rs. Replace its contents:

src/main.rs, which writes a closure double that returns n times 2, a closure greet whose body has several lines and builds Hello with the name in capitals, and a closure over_limit that compares an amount with a limit of 500 set before it, and prints what each returns.

src/main.rs
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 * 2 takes an i32 named n and returns n * 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 > limit uses limit, a variable of main, without taking it as a parameter.

Step 2: Run It​

Terminal
cargo run -q
Output
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:

src/main.rs
fn main() {
let double = |n| n * 2;
println!("{}", double(21));
println!("{}", double(2.5));
}
Terminal
cargo run -q
Output
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

A zsh terminal where cargo run -q prints 42, Hello, ADA!, true and false, then, for the changed file, fails with error E0308, expected integer, found floating-point number, with a note that the closure was earlier called with an integer.

What Happened​

  • 42 is double(21).
  • Hello, ADA!: greet turned the name into capitals and built the greeting.
  • true and false: 900 is over the limit of 500, and 120 isn't. The closure used limit from main.
  • The changed version didn't compile. Without a type, Rust took the type of n from the first call, double(21), which passes an integer, so double(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​

MistakeWhat happensDo 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 mutableDeclare it as let mut add: two calls then made count 2
An fn inside main that uses a variable of mainerror[E0434]: can't capture dynamic environment in a fn item, with a help to use the closure formWrite a closure instead
A return type without braces, as in |n: i32| -> i32 n * 2error: 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 suppliedPass one argument for each parameter

Troubleshooting​

SymptomLikely causeFix
expected because the closure was earlier called with an argument of type `{integer}` The closure has no parameter type, and two calls passed different typesGive the parameter its type, and pass values of that type
error: expected `{`, found `n` on a closureA return type with a body that isn't in bracesPut 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​