rust / intermediate
Snippet
Closures: Capturing Environment and Fn Traits
Rust closures are anonymous functions that can capture their environment. They implement one of three traits: Fn (borrows immutably), FnMut (borrows mutably), or FnOnce (takes ownership). Understanding these traits is essential for writing higher-order functions and effective memory management.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
fn main() {let x = 10;// Closure capturing by referencelet print_x = || println!("x = {}", x);print_x();// Closure capturing by mutable referencelet mut counter = 0;let increment = || {counter += 1;println!("counter = {}", counter);};increment();increment();// Higher-order function using Fnfn apply<F>(f: F) where F: Fn() {f();}apply(print_x);}
Breakdown
1
let x = 10;
Variable binding for later closure capture
2
let print_x = || println!("x = {}", x);
Closure capturing x by reference, implements Fn trait
3
let mut counter = 0;
Mutable counter for closure mutation demonstration
4
let increment = || { counter += 1; ... }
Closure capturing counter by mutable reference, implements FnMut
5
fn apply<F>(f: F) where F: Fn()
Generic function accepting any closure that implements Fn