Closure — anonymous function with captured environment.
Basic:
1let add = |a, b| a + b;2println!("{}", add(2, 3)); // 5
Capturing:
1let name = String::from("Alice");23// Borrow4let greet = || println!("Hello, {}!", name);5greet();67// Mutable borrow8let mut count = 0;9let mut inc = || count += 1;10inc();1112// Move13let name = String::from("Alice");14let greet = move || println!("Hello, {}!", name);15greet();
As argument:
1fn apply<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 {2 f(x)3}45let result = apply(|x| x * 2, 5);
Key: Closures capture environment, use move for ownership.