Closures: functions that remember their surroundings
A closure is an anonymous function you can store in a variable or pass to another function. It is written with pipes around the parameters: |x| x + 1. Unlike a normal fn, a closure can use variables from the scope where it was created. That is called capturing.
fn main() {
let add_one = |x: i32| x + 1; // types written out
let square = |x| x * x; // types inferred from first use
let tax_rate = 0.2;
let with_tax = |price: f64| price * (1.0 + tax_rate); // captures tax_rate
println!("{}", add_one(4));
println!("{}", square(7));
println!("{:.2}", with_tax(50.0));
let greet = |name: &str| {
let msg = format!("Hi, {}", name);
msg.len()
};
println!("{}", greet("Ferris"));
}5
49
60.00
10A closure with a block body works like a function body: the last expression is the return value.
Change tax_rate to 0.1 and predict the new output before running it.
square(7) and later square(2.5) is a type error: the closure already takes i32. If you need it to work on several types, write a generic fn instead.