Rust Closures Tutorial - Anonymous Functions, Capturing Variables & Iterators | Rust for Beginners
Video: Rust Closures Tutorial - Anonymous Functions, Capturing Variables & Iterators | Rust for Beginners by Taught by Celeste AI - AI Coding Coach
Watch full page →Rust Closures Tutorial - Anonymous Functions, Capturing Variables & Iterators
Closures in Rust are anonymous functions that can capture variables from their surrounding environment, enabling powerful functional programming patterns. This tutorial covers closure syntax, how they capture variables, the use of the move keyword for ownership transfer, and practical examples using iterators like map and filter.
Code
// Basic closure with inferred types
let add = |a, b| a + b;
println!("Add: {}", add(3, 5)); // Output: 8
// Closure with explicit type annotations
let multiply = |a: i32, b: i32| -> i32 { a * b };
println!("Multiply: {}", multiply(3, 5)); // Output: 15
// Capturing a variable from the environment
let x = 10;
let add_to_x = |y| x + y;
println!("Add to x: {}", add_to_x(5)); // Output: 15
// Using the move keyword to transfer ownership into the closure
let s = String::from("hello");
let consume = move || println!("Moved string: {}", s);
consume();
// println!("{}", s); // Error: s has been moved
// Using closures with iterators
let numbers = vec![1, 2, 3, 4, 5];
// Doubling each element using map
let doubled: Vec = numbers.iter().map(|x| x * 2).collect();
println!("Doubled: {:?}", doubled); // Output: [2, 4, 6, 8, 10]
// Filtering elements greater than 2
let filtered: Vec<&i32> = numbers.iter().filter(|&&x| x > 2).collect();
println!("Filtered: {:?}", filtered); // Output: [3, 4, 5]
Key Points
- Closures are anonymous functions defined with vertical bars enclosing parameters.
- Rust infers closure parameter and return types, but explicit annotations are also possible.
- Closures can capture variables from their defining environment by reference, mutable reference, or by value.
- The
movekeyword forces closures to take ownership of captured variables, enabling safe concurrency and longer lifetimes. - Closures integrate seamlessly with iterator methods like
mapandfilterfor concise data transformations.