Rust
Beginner
1 min read
Closures: Syntax and Capturing
Example
fn apply<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 {
f(x)
}
fn make_multiplier(factor: i32) -> impl Fn(i32) -> i32 {
move |x| x * factor // 'factor' is moved into the closure
}
fn main() {
// Basic closure syntax
let double = |x: i32| x * 2;
let add_three = |x| x + 3; // types inferred from use
println!("double(5) = {}", double(5));
println!("add_three(5) = {}", add_three(5));
// Closure capturing environment by immutable borrow
let offset = 10;
let add_offset = |x| x + offset;
println!("add_offset(5) = {} offset still = {offset}", add_offset(5));
// Closure capturing by mutable borrow
let mut total = 0;
let mut accumulate = |x: i32| { total += x; };
accumulate(1); accumulate(2); accumulate(3);
drop(accumulate); // release borrow so we can read total again
println!("total = {total}");
// move closure
let msg = String::from("hello from closure");
let greet = move || println!("{msg}");
greet();
// println!("{msg}"); // compile error: moved into closure
// Higher-order function
println!("apply double: {}", apply(double, 7));
println!("apply |x| x-1: {}", apply(|x| x - 1, 7));
// Returning a closure (factory)
let times7 = make_multiplier(7);
println!("times7(6) = {}", times7(6));
}