capypad
0 day streak
rust / intermediate
Snippet

Closures as Function Parameters with impl Fn

Closures can be passed as function parameters using trait bounds. The Fn trait represents closures that capture their environment by reference. By specifying Fn(i32) -> i32, we accept any closure that takes one i32 and returns an i32, regardless of how it captures variables internally.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
fn apply_twice<F>(f: F, value: i32) -> i32
where
F: Fn(i32) -> i32,
{
f(f(value))
}
 
fn main() {
let triple = |x: i32| x * 3;
let result = apply_twice(triple, 5);
println!("Result: {}", result); // 45 (triple applied twice)
}
Breakdown
1
fn apply_twice<F>(f: F, value: i32) -> i32
Generic function where F is a type parameter representing a callable
2
F: Fn(i32) -> i32,
F must implement Fn trait - a closure taking i32 and returning i32
3
f(f(value))
Applies the closure twice: first f(5)=15, then f(15)=45
4
let triple = |x: i32| x * 3;
Creates a closure that multiplies by 3 and stores it in triple
5
apply_twice(triple, 5)
Passes the closure to apply_twice - it is copied (Fn is Copy)