Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ REUSE THE IDEA
BUILD NOTE 28 / 53

Carry a little context.

Use anonymous functions and understand what they capture.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

01 Understand the contract

A closure can capture surrounding values by shared borrow, mutable borrow, or ownership. Rust infers the least demanding capture that fits the body, while move transfers captured values into the closure. Fn, FnMut, and FnOnce describe how a closure can be called: a consuming closure may be callable only once, while a read-only one can often be called repeatedly. Capturing ownership does not by itself mean a closure must be FnOnce-only; what the body does with the captured data matters.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/closures/src/main.rs
fn main() {
    let threshold = 10;
    let large = |value: &i32| *value > threshold;
    let values = [4, 12, 20];
    let selected: Vec<_> = values.into_iter().filter(large).collect();
    println!("{selected:?}");
}
↳ EXPECTED OUTPUT
[12, 20]
  1. 1

    The closure borrows threshold for its comparison.

  2. 2

    filter asks the closure whether each item should remain.

  3. 3

    collect materializes a new vector.

From the extracted rust-workbench folder
cargo run -p lesson_closures

03 Mind the boundary

04 Your next build

A SMALL MISSION

Use a mutable closure to count calls, then verify the count after its last use.

Reveal one possible solution +
solutions/closures/src/main.rs
fn main() {
    let mut calls = 0;
    let mut tick = || {
        calls += 1;
    };
    tick();
    tick();
    assert_eq!(calls, 2);
}

05 Check your reasoning

QUICK SIGNAL CHECK

What does move on a closure control?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.