A Rust closure is an anonymous function that captures variables around it. For each closure, the compiler builds an anonymous type close to a struct whose fields are the captured values. If the body only reads a value, the field is a shared reference; if it mutates the value, a mutable reference; if it consumes the value, the value itself. What the body does with the value also decides which of Fn, FnMut, and FnOnce the closure implements. The iterator adapters map and filter take such closures and wrap them in a struct — nothing is computed until a method like collect calls next.

I checked capture modes through closure sizes, and lazy evaluation through the order println! output appears in. Every example below was compiled with rustc 1.94.1, edition 2021, and run on aarch64-apple-darwin (Apple Silicon macOS). Sizes are for a 64-bit target.

Capture modes — shared reference, mutable reference, value

A closure captures by reference when its body only reads, by mutable reference when it writes, and by value when it gives ownership awayclosurestruct the compiler builds|| println!("hello")no fields · 0 bytes|| println!("{name}")&String · 8 bytes|| count += 1&mut i32 · 8 bytes|| drop(name)String · 24 bytesWhat the body does with a value decides the field type

I built four closures and measured each with size_of_val.

use std::mem::size_of_val;

fn main() {
    let name = String::from("wid");
    let mut count = 0;

    let nothing = || println!("hello");
    let read = || println!("{name}");
    let mut bump = || count += 1;

    println!("nothing = {} bytes", size_of_val(&nothing));
    println!("read    = {} bytes", size_of_val(&read));
    println!("bump    = {} bytes", size_of_val(&bump));

    nothing();
    read();
    bump();
    bump();
    println!("count = {count}");

    let consume = || drop(name);
    println!("consume = {} bytes", size_of_val(&consume));
    consume();
}
nothing = 0 bytes
read    = 8 bytes
bump    = 8 bytes
hello
wid
count = 2
consume = 24 bytes

nothing captures nothing and takes 0 bytes. read and bump take 8 bytes, the size of one pointer: they hold a &String and a &mut i32. consume holds the String itself (pointer, length, capacity) and takes 24 bytes, because drop(name) in its body needs ownership.

The Rust Reference lists the capture modes as immutable borrow (a shared reference here), mutable borrow, and move (with a special unique immutable borrow in between), and says a value is captured with the first mode compatible with how the body uses it. The closure borrows only as much as it needs.

Until a closure holding a mutable borrow is used for the last time, the original variable cannot be read. The borrowing rules from the references and borrowing post apply to closure fields as well.

fn main() {
    let mut count = 0;
    let mut bump = || count += 1;
    println!("{count}");
    bump();
}
error[E0502]: cannot borrow `count` as immutable because it is also borrowed as mutable
 --> capture_err.rs:4:16
  |
3 |     let mut bump = || count += 1;
  |                    -- ----- first borrow occurs due to use of `count` in closure
  |                    |
  |                    mutable borrow occurs here
4 |     println!("{count}");
  |                ^^^^^ immutable borrow occurs here
5 |     bump();
  |     ---- mutable borrow later used here
  |
  = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)

bump holds &mut count as a field and is used again on line 5, so it overlaps with the shared borrow on line 4. Moving the bump() call above the println! makes it compile.

move — by value, whatever the body does

With move, the closure stores the String and the i32 by value even though the body only reads them, so 16 bytes become 32|| println!("{name} {id}")&String&i3216 bytesmove || println!("{name} {id}")Stringi32 + pad32 bytesSizes from size_of_val; field order is not guaranteedid is Copy, so main can still use it after the move

With move, the closure takes the captured variables by value even when the body only reads them.

use std::mem::size_of_val;

fn main() {
    let name = String::from("wid");
    let id = 7;

    let by_ref = || println!("{name} {id}");
    println!("by_ref  = {} bytes", size_of_val(&by_ref));
    by_ref();

    let by_move = move || println!("{name} {id}");
    println!("by_move = {} bytes", size_of_val(&by_move));
    by_move();
    by_move();
    println!("id = {id}");
}
by_ref  = 16 bytes
wid 7
by_move = 32 bytes
wid 7
wid 7
id = 7

The bodies are the same, but by_ref holds two references for 16 bytes, while by_move holds a 24-byte String and a 4-byte i32 plus alignment padding for 32 bytes. I did not measure field order; the layout in the figure only matches the sizes. id is Copy, so the closure gets a copy and main can keep using it. name is a String and has moved, so using it after creating the move closure fails with E0382.

fn main() {
    let name = String::from("wid");
    let greet = move || println!("hi {name}");
    greet();
    println!("{name}");
}
error[E0382]: borrow of moved value: `name`
 --> move_err.rs:5:16
  |
2 |     let name = String::from("wid");
  |         ---- move occurs because `name` has type `String`, which does not implement the `Copy` trait
3 |     let greet = move || println!("hi {name}");
  |                 -------               ---- variable moved due to use in closure
  |                 |
  |                 value moved into closure here
4 |     greet();
5 |     println!("{name}");
  |                ^^^^ value borrowed here after move
  |
  = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider cloning the value before moving it into the closure
  |
3 ~     let value = name.clone();
4 ~     let greet = move || println!("hi {value}");
  |

move is required when the closure has to outlive the variables it captures. When a function returns a closure, the function’s locals are gone by the time it returns, so a closure that captured them by reference cannot be returned.

fn make_adder(n: i32) -> impl Fn(i32) -> i32 {
    |x| x + n
}

fn main() {
    let add5 = make_adder(5);
    println!("{}", add5(1));
}
error[E0373]: closure may outlive the current function, but it borrows `n`, which is owned by the current function
 --> return_err.rs:2:5
  |
2 |     |x| x + n
  |     ^^^     - `n` is borrowed here
  |     |
  |     may outlive borrowed value `n`
  |
note: closure is returned here
 --> return_err.rs:2:5
  |
2 |     |x| x + n
  |     ^^^^^^^^^
help: to force the closure to take ownership of `n` (and any other referenced variables), use the `move` keyword
  |
2 |     move |x| x + n
  |     ++++

The body x + n only reads n, so the compiler captured &n. Changing it to move |x| x + n, as the compiler suggests, puts a copy of n in the closure, and the program prints 6. Passing a closure to a thread needs move for the same reason; the Send and 'static requirements that come with it are out of scope here.

Fn, FnMut, FnOnce — what the body does with captured values

Every closure is FnOnce; one that does not move captured values out is also FnMut, and one that does not mutate them either is also FnFnOnce — called once (self)|| drop(name)consumes a valueFnMut — called many times (&mut self)|| count += 1mutatesFn — called many times (&self)|| println!("{name}")only readsmove || println!("{name}")plain fn doubleA function taking F: FnOnce accepts closures from all three areas

A function that takes a closure puts one of three traits on it as a bound. They differ in how the call receives the closure: Fn takes &self, FnMut takes &mut self, and FnOnce takes self. That is why a closure called through FnOnce is consumed by the call.

The body decides which trait a closure implements. According to the Call traits section of the Reference, every closure implements FnOnce; one that does not move captured values out also implements FnMut, and one that does not mutate them either also implements Fn. In std, Fn declares FnMut as a supertrait, and FnMut declares FnOnce. An Fn closure can be passed where FnMut or FnOnce is required, and an FnMut closure where FnOnce is required.

fn call_twice<F: Fn()>(f: F) {
    f();
    f();
}

fn call_twice_mut<F: FnMut()>(mut f: F) {
    f();
    f();
}

fn call_once<F: FnOnce()>(f: F) {
    f();
}

fn main() {
    let name = String::from("wid");
    let mut count = 0;

    call_twice(|| println!("read {name}"));
    call_twice_mut(|| count += 1);
    println!("count = {count}");

    call_once(|| println!("read {name}"));
    call_once(move || drop(name));
}
read wid
read wid
count = 2
read wid

A closure that only reads is Fn, so call_once accepts it too. The other direction is rejected. Here an FnMut closure that mutates goes where Fn is expected.

fn call_twice<F: Fn()>(f: F) {
    f();
    f();
}

fn main() {
    let mut count = 0;
    call_twice(|| count += 1);
}
error[E0594]: cannot assign to `count`, as it is a captured variable in a `Fn` closure
 --> fn_mut_err.rs:8:19
  |
1 | fn call_twice<F: Fn()>(f: F) {
  |                           - change this to accept `FnMut` instead of `Fn`
...
7 |     let mut count = 0;
  |         --------- `count` declared here, outside the closure
8 |     call_twice(|| count += 1);
  |     ---------- -- ^^^^^^^^^^ cannot assign
  |     |          |
  |     |          in this closure
  |     expects `Fn` instead of `FnMut`

A closure that consumes a value in an Fn position fails with E0507.

fn call_twice<F: Fn()>(f: F) {
    f();
    f();
}

fn main() {
    let name = String::from("wid");
    call_twice(|| drop(name));
}
error[E0507]: cannot move out of `name`, a captured variable in an `Fn` closure
 --> fn_err.rs:8:24
  |
7 |     let name = String::from("wid");
  |         ----   ------------------- move occurs because `name` has type `String`, which does not implement the `Copy` trait
  |         |
  |         captured outer variable
8 |     call_twice(|| drop(name));
  |                --      ^^^^ `name` is moved here
  |                |
  |                captured by this `Fn` closure
  |
help: `Fn` and `FnMut` closures require captured values to be able to be consumed multiple times, but `FnOnce` closures may consume them only once
 --> fn_err.rs:1:18
  |
1 | fn call_twice<F: Fn()>(f: F) {
  |                  ^^^^
help: consider cloning the value if the performance cost is acceptable
  |
8 |     call_twice(|| drop(name.clone()));
  |                            ++++++++

A closure that only implements FnOnce also refuses a second call when called directly, with no bound involved. The first call moves the closure value itself.

fn main() {
    let name = String::from("wid");
    let consume = || drop(name);
    consume();
    consume();
}
error[E0382]: use of moved value: `consume`
 --> once_err.rs:5:5
  |
4 |     consume();
  |     --------- `consume` moved due to this call
  |
note: closure cannot be invoked more than once because it moves the variable `name` out of its environment
 --> once_err.rs:3:27
  |
3 |     let consume = || drop(name);
  |                           ^^^^
note: this value implements `FnOnce`, which causes it to be moved when called
 --> once_err.rs:4:5
  |
4 |     consume();
  |     ^^^^^^^

move and FnOnce are separate things. move decides how values are captured; the Fn traits follow from what the body does with them. The Reference also notes that move closures may still implement Fn or FnMut. A plain function with a matching signature can be passed to an Fn bound as well.

fn call_twice<F: Fn()>(f: F) {
    f();
    f();
}

fn double(x: i32) -> i32 {
    x * 2
}

fn apply<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 {
    f(x)
}

fn main() {
    let name = String::from("wid");
    call_twice(move || println!("moved {name}"));

    let offset = 10;
    println!("{}", apply(double, 1));
    println!("{}", apply(|x| x + offset, 1));
}
moved wid
moved wid
2
11

The move closure, which took name by value, was called twice by call_twice. Its body only reads name, so it is Fn. When writing a function that takes a closure, I start from the widest bound, FnOnce, and narrow to FnMut if it must be called more than once, or to Fn if it must be called through a shared reference — that keeps the requirement on callers as small as possible. Generic bounds and impl Trait themselves were covered in the traits, generics, and dyn post.

The Iterator trait and next

An iterator is a type that implements the Iterator trait, which has one required method.

fn next(&mut self) -> Option<Self::Item>;

next returns Some while elements remain and None at the end. It takes &mut self because each call moves the internal position forward. Implementing one by hand shows that for is just repeated calls to next.

struct Countdown {
    remaining: u32,
}

impl Iterator for Countdown {
    type Item = u32;

    fn next(&mut self) -> Option<u32> {
        if self.remaining == 0 {
            return None;
        }
        self.remaining -= 1;
        Some(self.remaining + 1)
    }
}

fn main() {
    let mut countdown = Countdown { remaining: 2 };
    println!("{:?}", countdown.next());
    println!("{:?}", countdown.next());
    println!("{:?}", countdown.next());

    for n in (Countdown { remaining: 3 }) {
        print!("{n} ");
    }
    println!();
}
Some(2)
Some(1)
None
3 2 1

Only next was implemented, yet for works. The other methods — map, filter, collect and the rest — are default methods of the Iterator trait, so Countdown gets them as is.

iter, iter_mut, into_iter — how elements come out

iter yields &String, iter_mut yields &mut String, into_iter yields String, and only into_iter moves namesnames: Vec<String>"a""b".iter()&Stringread onlynames stays.iter_mut()&mut Stringmodify in placenames stays.into_iter()Stringtake the valuenames moved

A Vec has three methods that return an iterator, and I printed the Item type each one yields with type_name.

fn item_type<I: Iterator>(_: &I) -> &'static str {
    std::any::type_name::<I::Item>()
}

fn main() {
    let mut names = vec![String::from("a"), String::from("b")];

    println!("iter      -> {}", item_type(&names.iter()));
    println!("iter_mut  -> {}", item_type(&names.iter_mut()));

    for name in names.iter_mut() {
        name.push('!');
    }
    for name in names.iter() {
        print!("{name} ");
    }
    println!();

    let owned = names.into_iter();
    println!("into_iter -> {}", item_type(&owned));
    let joined: Vec<String> = owned.collect();
    println!("{joined:?}");
}
iter      -> &alloc::string::String
iter_mut  -> &mut alloc::string::String
a! b!
into_iter -> alloc::string::String
["a!", "b!"]

iter yields &String for reading, and iter_mut yields &mut String for modifying elements in place. In both cases names remains usable. into_iter takes self, consumes the Vec, and yields the String values themselves. for gets its iterator through IntoIterator::into_iter, and for x in &names, for x in &mut names, and for x in names build iterators with the same Item as iter, iter_mut, and into_iter. The last form moves names, so it cannot be used after the loop.

fn main() {
    let names = vec![String::from("a"), String::from("b")];
    for name in names {
        println!("{name}");
    }
    println!("{}", names.len());
}
error[E0382]: borrow of moved value: `names`
   --> into_iter_err.rs:6:20
    |
  2 |     let names = vec![String::from("a"), String::from("b")];
    |         ----- move occurs because `names` has type `Vec<String>`, which does not implement the `Copy` trait
  3 |     for name in names {
    |                 ----- `names` moved due to this implicit call to `.into_iter()`
...
  6 |     println!("{}", names.len());
    |                    ^^^^^ value borrowed here after move
    |
note: `into_iter` takes ownership of the receiver `self`, which moves `names`
   --> …/library/core/src/iter/traits/collect.rs:310:18
    |
310 |     fn into_iter(self) -> Self::IntoIter;
    |                  ^^^^
help: consider iterating over a slice of the `Vec<String>`'s content to avoid moving into the `for` loop
    |
  3 |     for name in &names {
    |                 +

I shortened the standard library path. The compiler points at the .into_iter() call that for inserted and suggests &names instead.

Adapters are lazy

Methods like map, filter, and take that take an iterator and return an iterator are called adapters. An adapter computes nothing when it is called. Call map without using the result, and the println! inside the closure never runs; the compiler warns instead.

fn main() {
    let numbers = vec![1, 2, 3];
    numbers.iter().map(|n| {
        println!("map {n}");
        n * 10
    });
    println!("done");
}
warning: unused `Map` that must be used
 --> lazy_warn.rs:3:5
  |
3 | /     numbers.iter().map(|n| {
4 | |         println!("map {n}");
5 | |         n * 10
6 | |     });
  | |______^
  |
  = note: iterators are lazy and do nothing unless consumed
  = note: `#[warn(unused_must_use)]` (part of `#[warn(unused)]`) on by default
help: use `let _ = ...` to ignore the resulting value
  |
3 |     let _ = numbers.iter().map(|n| {
  |     +++++++
done

The warning comes from #[must_use = "iterators are lazy and do nothing unless consumed"] on the Map struct. The run printed only done.

Each time collect calls next, one element passes through map, filter, and take; once take is full, 3 and 4 are never pulleditermapfiltertake(1)collectcollect calls next() on take → filter → map → iter110✗ dropped220✓ 2020[20]3next() never called4next() never calledOne element goes through the whole chain before the next is pulled

The work happens when something that consumes the iterator — collect, sum, a for loop — calls next. The consumer at the end calls next on the adapter before it, which calls next on the one before that, and so on. Some std methods such as sum are implemented with fold and do not call next directly, but elements still pass through the chain one at a time in the same order. To see which stage each element passes through, I put a println! in both map and filter.

fn main() {
    let numbers = vec![1, 2, 3, 4];
    let picked: Vec<i32> = numbers
        .iter()
        .map(|n| {
            println!("map    {n}");
            n * 10
        })
        .filter(|n| {
            println!("filter {n}");
            n % 20 == 0
        })
        .take(1)
        .collect();
    println!("picked = {picked:?}");
}
map    1
filter 10
map    2
filter 20
picked = [20]

map does not process all four elements before filter takes over. 1 went through map and filter and was dropped, and only then was 2 pulled. Once 20 filled take(1), take answered the next next with None without calling the stage before it, so 3 and 4 never reached map. No intermediate Vec is built, and only the elements needed are computed.

The signature of map shows the bound an adapter puts on its closure.

fn map<B, F>(self, f: F) -> Map<Self, F>
where
    Self: Sized,
    F: FnMut(Self::Item) -> B,

map calls the closure once per element, so FnOnce will not do; it asks for FnMut rather than Fn so the closure may change state. A closure that mutates a captured variable can therefore be passed.

fn main() {
    let words = vec!["fig", "apple", "banana"];
    let mut calls = 0;
    let lengths: Vec<usize> = words
        .iter()
        .map(|w| {
            calls += 1;
            w.len()
        })
        .collect();
    println!("{lengths:?}, calls = {calls}");
}
[3, 5, 6], calls = 3

An adapter chain is a struct with closures as fields

The iter().map().filter() chain is nested structs holding the Iter and both closures, 24 bytes in totalFilter<…> — 24 bytesMap<…> — 16 bytesslice::Iter<i32>two pointers · 16 bytes|n| n * 10captures nothing · 0 bytes|n| *n > thresholdcaptures &threshold · 8 bytes

Adapters can defer work because they hold the previous iterator and the closure as fields. I built a chain and printed its size and type name.

use std::mem::size_of_val;

fn main() {
    let numbers = vec![1, 2, 3, 4];
    let threshold = 15;

    let iter = numbers.iter();
    println!("iter          = {} bytes", size_of_val(&iter));

    let mapped = numbers.iter().map(|n| n * 10);
    println!("map           = {} bytes", size_of_val(&mapped));

    let filtered = numbers.iter().map(|n| n * 10).filter(|n| *n > threshold);
    println!("map + filter  = {} bytes", size_of_val(&filtered));
    println!("{}", std::any::type_name_of_val(&filtered));

    let total: i32 = filtered.sum();
    println!("sum = {total}");
}
iter          = 16 bytes
map           = 16 bytes
map + filter  = 24 bytes
core::iter::adapters::filter::Filter<core::iter::adapters::map::Map<core::slice::iter::Iter<'_, i32>, adapter_size::main::{{closure}}>, adapter_size::main::{{closure}}>
sum = 90

The type name has the same nesting as the figure: Filter<Map<Iter<i32>, closure>, closure>. slice::Iter is 16 bytes, and the map closure captures nothing and takes 0 bytes, so Map is 16 bytes too. The filter closure captures &threshold and adds 8 bytes. The closure sizes from the first section show up directly in the size of the chain.

Every closure has its own type, so monomorphization makes a copy of Filter and Map for each closure type. The closure to call is known at compile time, which makes inlining possible. I did not inspect the generated code or measure run time in this post.

collect — the result type has to be given

collect consumes an iterator and builds a collection. What it builds is decided by the return type, so without a type the code does not compile.

fn main() {
    let numbers = vec![1, 2, 3];
    let doubled = numbers.iter().map(|n| n * 2).collect();
    println!("{doubled:?}");
}
error[E0283]: type annotations needed
    --> collect_err.rs:3:9
     |
   3 |     let doubled = numbers.iter().map(|n| n * 2).collect();
     |         ^^^^^^^                                 ------- type must be known at this point
     |
     = note: cannot satisfy `_: FromIterator<i32>`
note: required by a bound in `collect`
    --> …/library/core/src/iter/traits/iterator.rs:2022:19
     |
2022 |     fn collect<B: FromIterator<Self::Item>>(self) -> B
     |                   ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Iterator::collect`
help: consider giving `doubled` an explicit type
     |
   3 |     let doubled: Vec<_> = numbers.iter().map(|n| n * 2).collect();
     |                ++++++++

The return type B of collect can be any type that implements FromIterator<Self::Item>. Writing only the collection and leaving the element type as _ is enough. The same collect builds a Vec, a HashMap, or a String.

use std::collections::HashMap;

fn main() {
    let words = vec!["fig", "apple", "banana"];

    let lengths: Vec<usize> = words.iter().map(|w| w.len()).collect();
    let by_len: HashMap<usize, &str> = words.iter().map(|w| (w.len(), *w)).collect();
    let initials: String = words.iter().map(|w| w.chars().next().unwrap()).collect();

    println!("{lengths:?}");
    println!("{:?}", by_len.get(&5));
    println!("{initials}");
}
[3, 5, 6]
Some("apple")
fab

An iterator of (key, value) tuples collects into a HashMap, and an iterator of char into a String. Either way, it is this collect call that actually pulls the elements through the chain.

Wrapping up

A closure turned out to be a struct whose fields are what it captures. read, which only reads, held an 8-byte reference; consume, which consumes a String, held the 24-byte String. move changes only the capture mode to by-value, and a move closure whose body only reads is still Fn. Fn, FnMut, and FnOnce follow from whether the body reads, mutates, or consumes what it captured.

Iterators have the same structure. map and filter each stack one more struct holding the previous iterator and a closure, and elements pass through the chain one at a time when collect calls next. Once take(1) was full, 3 and 4 were never even pulled. Knowing what a closure holds and when an adapter calls it is, as I see it, what makes a one-line chain readable.

References