rust / beginner
Snippet
Closures: Anonymous Functions in Rust
Closures are anonymous functions you can assign to variables or pass to functions. They can infer parameter and return types automatically, or you can annotate them explicitly. Closures can capture variables from their surrounding scope, which is useful for custom operations. They're commonly used with iterator methods like map, filter, and collect.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fn main() {// Basic closure with type inferencelet add = |a, b| a + b;println!("5 + 3 = {}", add(5, 3));// Closure with explicit typeslet multiply = |x: i32, y: i32| -> i32 { x * y };println!("6 * 7 = {}", multiply(6, 7));// Closure that captures environmentlet factor = 10;let scale = |val| val * factor;println!("5 scaled by {} = {}", factor, scale(5));// Using closures with iteratorslet numbers = vec![1, 2, 3, 4, 5];let doubled: Vec<i32> = numbers.iter().map(|x| x * 2).collect();println!("Doubled: {:?}", doubled);}
Breakdown
1
let add = |a, b| a + b;
Simple closure that infers types from usage
2
let multiply = |x: i32, y: i32| -> i32 { x * y }
Closure with explicit type annotations
3
let scale = |val| val * factor;
Closure capturing factor from outer scope
4
numbers.iter().map(|x| x * 2).collect()
Chaining iterator methods with closures