capypad
0 day streak
rust / beginner
Snippet

Closures in Rust

Closures are anonymous functions that can capture their environment. They are defined with pipe syntax |x|. Unlike regular functions, closures can infer parameter types. Methods like fold() combine all elements using a closure, demonstrating functional programming patterns in Rust.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
fn main() {
let add = |x: i32, y: i32| -> i32 { x + y };
let multiply = |x, y| x * y;
println!("Add: {}", add(3, 4));
println!("Multiply: {}", multiply(5, 6));
let numbers = vec![1, 2, 3, 4, 5];
let sum = numbers.iter().fold(0, |acc, x| acc + x);
println!("Sum: {}", sum);
}
Breakdown
1
|x: i32, y: i32| -> i32 { x + y }
Closure with explicit parameter and return types
2
|x, y| x * y
Closure with inferred types (shorter syntax)
3
.fold(0, |acc, x| acc + x)
Reduces vector to single value by accumulating with closure