RRust By Example
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

This example demonstrates how to use closures basic in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

Browse more examples in the functions category to build a complete understanding of this topic.

More Functions Examples