Rust Closures
Closures
In the Functions chapter, you created functions with the fn keyword and a name.
A closure is a small function without a name. You can store it in a variable, and call it just like a normal function. Closures are often used for short pieces of code that you give to other functions and methods.
Create a Closure
Write the parameters between two vertical bars | |, followed by the code that returns a value:
Example
let add_one = |x| x + 1;
let add = |a: i32, b: i32| a + b;
println!("{}", add_one(5));
println!("{}", add(2, 3));
Try it Yourself »
add_one takes one parameter x, and returns x + 1. Rust can often find the types by itself, but you can also write them, like in add.
If a closure needs more than one line of code, put the code inside curly braces { }, just like the body of a function.
Closures Can Use Nearby Variables
Unlike functions, closures can use variables from the code around them. This is called capturing a variable:
Example
let bonus = 10;
let add_bonus = |score: i32| score + bonus;
println!("{}", add_bonus(50));
println!("{}", add_bonus(75));
Try it Yourself »
The closure uses bonus, which was created outside the closure.
A normal function cannot do this. If you try, you get an error:
Example
let bonus = 10;
fn add_bonus(score: i32) -> i32 {
score + bonus // Error
}
println!("{}", add_bonus(50));
Try it Yourself »
The error message suggests the fix: use the closure form instead.
Closures and Vector Methods
Many methods take a closure as a parameter. For example, retain() keeps only the items where the closure returns true:
Example
let mut scores = vec![40, 95, 70, 15, 60];
scores.retain(|score| *score >= 50);
println!("{:?}", scores);
Try it Yourself »
retain() gives the closure a reference to each item, so we write *score to get the number itself.
Why Use Closures?
- To write short functions right where you need them
- To use variables from the surrounding code
- To tell methods like
retain()what to do