Free preview.You're sampling one lesson — enroll free to unlock all 10 lessons and track your progress.
Enroll free
lesson

Closures and Higher-Order Functions

Closures and Higher-Order Functions

In this lesson — part of Advanced Features — you'll learn closures and higher-order functions in Rust and why it matters in real work.

Why it matters

Functions that take or return functions unlock concise, composable code.

Key ideas

  • Functions as values
  • map / filter / reduce
  • Callbacks
  • Composition

In practice

Here's how it looks in idiomatic Rust:

let nums = vec![1, 2, 3, 4, 5, 6];
let evens_squared: Vec<i32> = nums
    .iter()
    .filter(|&&n| n % 2 == 0) // keep even numbers
    .map(|&n| n * n)          // square them
    .collect();
println!("{:?}", evens_squared); // [4, 16, 36]

Rust note: Iterator adapters like map and filter are lazy — nothing runs until a consuming method such as collect drives the chain, which lets the compiler fuse them into a single tight loop.

Try it yourself

Exercise: In Rust, use map and filter to get the squares of the even numbers.

Recap

You now understand closures and higher-order functions and can apply it in Rust. Mark this lesson complete and continue to the next one.