rust / intermediate
Snippet
Closures: Capturing Environment and Function Traits
Rust closures capture variables from their environment. FnMut allows mutation of captured variables, Fn consumes them, and FnOnce takes ownership. Generic bounds let you write functions that accept different closure types.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
fn apply_with_log<F, T>(mut f: F, value: T) -> TwhereF: FnMut(T) -> T,{println!("Before: {:?}", value);let result = f(value);println!("After: {:?}", result);result}fn main() {let multiplier = 3i32;let increment = 10i32;let mut combined = |x: i32| -> i32 {x * multiplier + increment};let result = apply_with_log(combined, 5);println!("Final result: {}", result);let numbers = vec![1, 2, 3, 4, 5];let sum: i32 = numbers.iter().map(|x| x * multiplier).sum();println!("Sum: {}", sum);}
Breakdown
1
FnMut(T) -> T
FnMut can mutate captured environment, returns transformed value
2
let multiplier = 3i32;
Variable captured by closure, lives in closure's environment
3
let mut combined = |x: i32| -> i32 { ... }
Closure captures both multiplier and increment from scope
4
numbers.iter().map(|x| x * multiplier)
Closure passed to iterator, captured multiplier used inline