intermediateFunctions
Closures Basic
Anonymous functions that capture their environment.
Closures Basic
Anonymous functions that capture their environment.
Difficulty
Intermediate
Code
rust
fn main() {
let add = |a, b| a + b;
println!("3 + 5 = {}", add(3, 5));
let name = String::from("Rust");
let greet = || println!("Hello, {}!", name);
greet();
let nums = vec![1, 2, 3];
let sum: i32 = nums.iter().sum();
println!("sum = {}", sum);
}Explanation
Closures capture their environment. Use |args| body syntax.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the functions category to build a complete understanding of this topic.