Sebastian KaiserA personal engineering notebook

The notebook

The Iterator Is the State Machine

I can read a chain of enumerate(), filter(), and take() and understand what it asks for. I find it harder to picture what is actually running. Does each step traverse the data again? What does the chain borrow, and what work stops when we stop asking for values?

We'll build a small adapter, extend the pattern to prefix sums, and follow a query over borrowed telemetry records. The aim is to understand how the Iterator contract lets these pieces compose, and how ownership and dispatch affect the code we can write. That also gives us a basis for deciding when an ordinary iterator is enough and when asynchronous streams or coroutines help.

C++ ranges provide a useful comparison because they support lazy composition too. Looking at both languages helps distinguish the techniques they share from Rust's compile-time checks on borrowing. This gives us a way to judge the safety and potential costs of an iterator-based design, including which performance claims still need measurement.

I'll assume you can follow a for loop and have met map or filter in some language. You don't need to know Rust's trait system yet. The examples use Rust 2021 or later.

If you prefer to start with a data-processing task, Processing JSON with Rust follows nested Olympic records into a medal ranking. The iterator discussion here takes a closer look at the state and borrowing behind those kinds of chains.

How Rust iterators work

Here are four values, printed with their positions:

rustenumerate() adds a position to each value.Link
fn main() {
    for (index, value) in [1, 2, 3, 4]
        .into_iter()
        .enumerate()
    {
        println!("{index}: {value}");
    }
}

The output starts at 0: 1 and ends at 3: 4. Somewhere, something remembers which value comes next and which index to attach to it.

Rust's iteration protocol puts that responsibility in the iterator. Its required interface is small:fn:1

rustThe required part of Iterator, with its provided methods omitted.Link
pub trait Iterator {
    type Item;

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

A trait describes behavior a type can provide. Here, Item names the type of value it produces. next() asks for one value and returns either Some(value) or None. The &mut self parameter lets the iterator change its own state while answering.

A for loop first asks IntoIterator to turn its input into an iterator, then repeatedly asks for the next value. For this simple array, we can sketch the loop like this:fn:2

rustA sketch of the iteration behavior, not the complete language desugaring.Link
let values = [10, 20, 30];
let mut iterator = IntoIterator::into_iter(values);

while let Some(value) = iterator.next() {
    println!("{value}");
}

The loop stops at the first None. It doesn't need to know whether advancing means moving through an array, following a list, or reading from a file.

Does None always mean the iterator has finished forever?

The Iterator contract allows an implementation to return Some again after returning None. A for loop still stops at that first None. If you need later calls to keep returning None, fuse() supplies that behavior. Iterators implementing FusedIterator already promise it.fn:3

This becomes relevant when we reach asynchronous streams: None is not a general-purpose instruction to wait and try again later.

Composing iterators with adapters

An adapter wraps an iterator and implements Iterator itself. That shared interface lets us connect adapters: each one can use another as its source, without knowing how that source obtains its values.

To add a position, our wrapper needs to hold the source iterator and a counter:

rustA small numbering adapter. The counter starts at zero when we construct it.Link
struct Indexed<I> {
    source: I,
    index: usize,
Note

State between calls. The wrapper owns its source iterator and a counter. The source may itself borrow a collection; storing it here preserves that relationship.

}

impl<I: Iterator> Iterator for Indexed<I> {
Note

The same contract on both sides. I must implement Iterator, and Indexed<I> implements it too. Another adapter can use this wrapper as its source.

    type Item = (usize, I::Item);

    fn next(&mut self) -> Option<Self::Item> {
        let value = self.source.next()?;
Note

Ask the source for one item. ? returns None if the source has no item on this call. The counter advances only after an item is obtained.


        let index = self.index;
        self.index += 1;

        Some((index, value))
    }
}

I stands for whichever iterator we wrap. The bound I: Iterator lets us call its next() method, and I::Item names the type it produces. Our adapter returns a pair: a position and that source item. Because Indexed<I> also implements Iterator, it gets the trait's provided methods, including filter() and take().

The ? after self.source.next() returns None immediately if the source returned None. Otherwise, it extracts the value. We save the current index, increment the counter for next time, and return the pair.

We can construct one with the counter set to zero and step through it ourselves:

rustEach call advances the source and the counter held by the same object.Link
let mut indexed = Indexed {
    source: [10, 20].into_iter(),
    index: 0,
};

assert_eq!(indexed.next(), Some((0, 10)));
assert_eq!(indexed.next(), Some((1, 20)));
assert_eq!(indexed.next(), None);

The state persists in these fields between calls to next(). The method returns each time; the next call uses the values left by the previous one.

Rust's standard-library Enumerate stores the same two pieces of state. It also implements shortcuts for operations such as nth(), fold(), and try_fold(). We will come back to why those matter.fn:4

A counter still has a limit

The example uses usize, just as Enumerate does. Its index can overflow on a sufficiently long sequence. The public enumerate() documentation says that enumeration can panic or produce an incorrect count when the counter overflows, with a panic guaranteed when overflow checks are enabled. This adapter is a model of ordinary enumeration, not an arbitrary-precision counter.fn:5

Prefix sums

The same structure can produce prefix sums. Keep a running total alongside the source, add each incoming value, and yield the new total. For 3, 1, 4, 2, the prefix sums are 3, 4, 8, 10.

rustA custom prefix-sum adapter composes with the standard enumerate() and take() adapters.Link
struct PrefixSums<I> {
    source: I,
    total: u64,
}

impl<I: Iterator<Item = u64>> Iterator for PrefixSums<I> {
    type Item = u64;

    fn next(&mut self) -> Option<Self::Item> {
        self.total += self.source.next()?;
Note

Update the retained total. Each successful pull adds one source value. The same field holds 3, then 4, then 8 as the caller advances.

        Some(self.total)
    }
}

let sums: Vec<_> = PrefixSums {
    source: [3u64, 1, 4, 2].into_iter(),
    total: 0,
}
.enumerate()
.take(3)
Note

Let the consumer stop the work. take(3) stops before asking for a fourth sum. The final input, 2, is not read by this chain.

.collect();

assert_eq!(sums, vec![(0, 3), (1, 4), (2, 8)]);

This time the bound is narrower: the source must produce u64 values so we can add them to the total. The adapters after it still work through Iterator. enumerate() numbers the sums, and take(3) stops the chain before the last input is read. Neither needs to know how PrefixSums maintains its total.

As with the index counter, a reusable numeric adapter needs a policy for overflow. These small sums fit in u64. The standard library also provides scan(), which can express the same running total using stored state and a closure.fn:6

Ask for two matches

Now suppose we want the first two even values and their positions in the original input:

rustTwo results retain their original positions; inspect() counts three source values.Link
let values = [10, 11, 12, 13, 14];
let mut examined = 0;

let result: Vec<_> = values
    .into_iter()
    .inspect(|_| examined += 1)
    .enumerate()
    .filter(|(_, value)| value % 2 == 0)
    .take(2)
    .collect();

assert_eq!(examined, 3);
assert_eq!(result, vec![(0, 10), (2, 12)]);

enumerate() produces pairs. filter() keeps pairs whose value is even. Its predicate borrows each item as &Self::Item to test it; an accepted item is then passed on by value. With borrowed source items, that test adds another layer of references.fn:7 take(2) allows at most two items through, and collect() gathers them into a vector.

It is easy to imagine a separate pass at every dot: number all five values, put the even ones somewhere, then copy the first two. These adapters can instead pass requests and values through the chain without building those intermediate collections.fn:8

Think of asking the outer iterator for a match. It asks its source, which eventually reaches the array. The value 10 comes back with index 0, passes the filter, and becomes the first result.

The second request takes more work. 11 gets index 1 but fails the filter. The filter asks again, receives (2, 12), and accepts it. Once take(2) has supplied two results, it stops asking the source for more.

A take-filter-enumerate-source chain retains an output allowance, an even predicate, a position counter, and an input cursor. The first request accepts 10 at position 0. The second rejects 11 at position 1, then accepts 12 at position 2. Take has no outputs remaining, so 13 and 14 are not pulled.
Figure 1: Requests travel toward the source; accepted items return to the consumer. The second output needs two source reads. This is a semantic trace, not a literal optimized call graph.

The last two values aren't pulled through inspect(). Constructing the adapter chain didn't scan the input; consuming it caused the work. The final vector has storage of its own, but there is no vector between each adapter.

There is a limit to this control. Asking for one output can require examining many inputs. A filter over an infinite sequence with no matches never returns a match. Calling take(2) limits the number of outputs; it does not promise two source reads, a time limit, or a bounded amount of work.

Does the order matter?

Move enumerate() after the filter:

rustFiltering first numbers the surviving values, not their original positions.Link
let values = [10, 11, 12, 13, 14];

let result: Vec<_> = values
    .into_iter()
    .filter(|value| value % 2 == 0)
    .enumerate()
    .take(2)
    .collect();

assert_eq!(result, vec![(0, 10), (1, 12)]);

Now 12 has index 1. Only the surviving values reach the counter. In a diagnostic tool, that could turn an original record position into a match number. Both are useful, but we need to choose which one we mean.

Keep the records where they are

Numbering works the same way whether the source produces owned values or references. The difference travels through Item:

Expression Item type What the loop receives
names.iter() &String A shared reference to each string
names.iter_mut() &mut String An exclusive reference to each string
names.into_iter() String Ownership of each string from this vector

Here are all three with the same adapter:

rustThe first two loops borrow the vector; the last consumes it.Link
let mut names = vec![
    String::from("Alice"),
    String::from("Bob"),
];

// Borrow the elements.
for (i, name) in names.iter().enumerate() {
    println!("{i}: {name}");
}

// Mutably borrow the elements.
for (_, name) in names.iter_mut().enumerate() {
    name.push('!');
}

// Transfer ownership of the elements.
for (i, name) in names.into_iter().enumerate() {
    println!("{i}: {name}");
}

The last loop moves the strings out of the vector. It doesn't clone their contents, and we cannot use names afterward as though it still owned them. In the earlier loops, Rust checks that uses of the references respect their lifetimes and exclusive access requirements.fn:9

enumerate() doesn't need separate code for each case. Its pair contains I::Item, whatever that happens to be. It adds a counter while leaving the ownership relationship intact.

Ownership also determines cleanup. When we drop an adapter, its owned fields are dropped too, including the source iterator and any closure state. If a chain consumes a vector with into_iter(), dropping it also drops the vector iterator's unconsumed elements. A chain built with iter() only borrows the vector; dropping that chain leaves the elements in place.fn:10 Early termination stops further pulls, but cleanup can still do work.

A borrowed telemetry query

Consider readings already loaded into a buffer. We want unverified readings above a latency threshold, with their original positions. We can offer that search without copying matching records into another collection:

rustReturning a borrowed iterator lets the caller choose how many matches to inspect.Link
#[derive(Debug)]
struct Reading {
    device_id: u64,
    latency_ms: u32,
    verified: bool,
}

fn suspicious<'a>(
    readings: &'a [Reading],
    threshold_ms: u32,
) -> impl Iterator<Item = (usize, &'a Reading)> + 'a {
Note

Borrow from the caller's buffer. The yielded &'a Reading points into readings. Returning this iterator does not copy the records or extend the input's lifetime.

    readings
        .iter()
        .enumerate()
        .filter(move |(_, reading)| {
Note

Keep the threshold with the predicate. move captures threshold_ms by value. Since u32 is Copy, the closure keeps a copy; the source iterator still borrows the readings.

            reading.latency_ms > threshold_ms
                && !reading.verified
        })
}
Inspect the sample readings and call site
rustUse this main() with Reading and suspicious() above.Link
fn main() {
    let readings = [
        Reading {
            device_id: 101,
            latency_ms: 150,
            verified: true,
        },
        Reading {
            device_id: 102,
            latency_ms: 400,
            verified: false,
        },
        Reading {
            device_id: 103,
            latency_ms: 350,
            verified: false,
        },
    ];

    for (index, reading) in suspicious(&readings, 250).take(2) {
Note

Choose how many matches to inspect. The first reading is verified and excluded. This call prints the entries at positions 1 and 2 without collecting them into a new vector.

        println!("{index}: {reading:?}");
    }
}

The function describes how to find a reading. Its caller can ask for two, find the first, or count every match. Returning an iterator keeps that choice open.

The lifetime label 'a ties the references in the results to the borrowed input. It doesn't extend the life of the buffer or copy it somewhere safe. If a caller tries to keep using the search after the readings have gone away, the program fails to compile.

The move keyword makes the closure capture threshold_ms by value. Because u32 implements Copy, the closure stores a copy of the threshold instead of borrowing the function's local variable. The readings remain borrowed through the source iterator.fn:11

Keep a result while asking for another

Using the same readings, we can retain two matches and drop the search before using them:

rustReturned references remain usable after the iterator is dropped, while the readings stay valid.Link
let mut matches = suspicious(&readings, 250);

let first = matches.next().expect("first matching reading");
Note

Keep a result while advancing. first borrows a reading in the input buffer. It does not retain the temporary mutable borrow used to advance matches, so the next call is allowed.

let second = matches.next().expect("second matching reading");

drop(matches);
Note

Drop the search, keep the references. The iterator owns its adapter state, but only borrows the readings. Destroying that state does not destroy the caller's buffer.


println!("{first:?}");
println!("{second:?}");

Each call briefly borrows the iterator mutably so it can advance. The returned references borrow readings, not the iterator object. Holding the first result doesn't keep that call's mutable borrow of the iterator open, so we can ask for another. Dropping the iterator leaves both references usable as long as the underlying readings remain valid.fn:12

The signature separates these lifetimes. Item is fixed for the iterator type; it isn't parameterized by the temporary borrow of each next() call. In this search it contains &'a Reading, with 'a tied to the input slice. A mutable iterator must also make it safe to retain several results, for example by yielding references to distinct elements.

That is a limit on what ordinary Iterator can express. It cannot generally lend out a reference into its own scratch buffer and then overwrite that buffer on the next call while the reference is still in use. Such an API needs a different ownership arrangement, or a lending-style contract that ties each result to the call's borrow. We don't need that here: the caller already owns the buffer.

impl Iterator hides a concrete return type that would be awkward to write out. The compiler still knows that type, including the closure and the wrapped iterators. Returning it this way does not introduce a boxed object or a virtual method call.fn:13

Static and dynamic dispatch

The trait tells us what an iterator can do. Rust lets us choose how a call reaches the implementation. Here are two functions asking for the same thing:

Two ways to call next() Both functions borrow an existing iterator. The dynamic version uses a trait object.

Static dispatch

rustA concrete generic parameter.Link
fn next_static<I: Iterator<Item = u64>>(
    source: &mut I,
) -> Option<u64> {
    source.next()
}

The compiler can specialize the function for the concrete iterator type.

Dynamic dispatch

rustA borrowed trait object.Link
fn next_dynamic(
    source: &mut dyn Iterator<Item = u64>,
) -> Option<u64> {
    source.next()
}

The trait-object reference supplies the vtable metadata used to find the method.

With next_static, the compiler knows the concrete I and can specialize the function for it. This is static dispatch.fn:14 With next_dynamic, the function accepts a trait object. Its reference carries a pointer to the iterator state and vtable metadata used to find the method at runtime. This is dynamic dispatch.fn:15

The iterator still holds its state in either case. Dispatch changes how we reach the method, not who drives the sequence or whether it is lazy.

Notice that next_dynamic borrows an iterator. It doesn't allocate one. We can pass a reference to an iterator already stored in a local variable. Heap allocation and dynamic dispatch are separate choices.

For our telemetry query, each adapter and closure has a concrete type. suspicious() returns the resulting chain through impl Iterator, which hides its name without erasing that type. The compiler keeps the information needed to specialize calls and consider inlining them.fn:13 We haven't needed a runtime choice of implementation between stages.

A concrete wrapper can still contain a dynamically dispatched iterator. Adding take() around a trait object doesn't make calls to that underlying source static.

When would a boxed iterator be useful?

Suppose a query can return every value or only even ones, depending on a setting read at runtime:

rustTwo concrete iterator types share one boxed return type, while the input remains borrowed.Link
fn choose_values<'a>(
    values: &'a [u64],
    only_even: bool,
) -> Box<dyn Iterator<Item = u64> + 'a> {
    if only_even {
        Box::new(values.iter().copied().filter(|x| x % 2 == 0))
    } else {
        Box::new(values.iter().copied())
    }
}

The branches construct different types: one includes a filter and the other doesn't. Box<dyn Iterator<Item = u64> + 'a> gives them a common return type. The box owns the iterator state; the slice remains borrowed. The lifetime bound keeps that borrow valid, and Item = u64 tells callers what either implementation produces.

A plain impl Iterator return cannot hide a different concrete type in each branch. For this particular condition we could instead use one filter with a configurable predicate. An enum could also represent a fixed set of alternatives. A trait object becomes useful when we want a common interface without making that set part of its type.

Here the box supplies owned heap storage for the iterator, not a newly allocated record on every call. The earlier &mut dyn Iterator example supplies dynamic dispatch without that storage choice. Both retain the usual ownership and borrowing checks.

Static specialization can increase generated code size and compilation work when many concrete types use the same generic code. Dynamic dispatch can let a consumer share one implementation across those types. An indirect call may make inlining harder, although the optimizer can sometimes recover the target. If this trade-off matters to the application, it needs measurement.fn:14, fn:16

Which iterator methods can a trait object call?

Traits must satisfy Rust's dyn compatibility rules to support trait objects. Iterator does, once we specify its associated Item type. Its next() method can be called through the vtable. Many generic adapter and consumer methods instead require Self: Sized, which excludes those methods from the dynamically callable interface.fn:17

That doesn't prevent further composition. A sized wrapper such as Box<dyn Iterator<Item = u64>> or &mut dyn Iterator<Item = u64> itself implements Iterator. We can add adapters around it. The outer adapter has a concrete type, while requests reaching the erased source still use its dynamic interface. A generic wrapper doesn't automatically make every call inside it static.fn:1

For a visual tour of trait-object pointers, see Sofía Belén López Vicens's Visualizing Rust's VTables: How dyn Trait Works in Memory. Exact byte layouts and vtable slot offsets should not be treated as a stable Rust ABI.fn:18

Compiler optimization

An iterator chain can compile to code similar to a hand-written loop. Rust specializes generic code for concrete types through monomorphization. Inlining can then bring operations from different adapters together so the optimizer can work across them.fn:14

For example, these functions calculate the same sum. The wrapping operations make overflow behavior explicit:

rustA loop that squares even values and adds them with wrapping arithmetic.Link
pub fn manual(input: &[u64]) -> u64 {
    let mut sum = 0u64;

    for &x in input {
        if x % 2 == 0 {
            sum = sum.wrapping_add(x.wrapping_mul(x));
        }
    }

    sum
}
rustThe same calculation expressed as an iterator chain.Link
pub fn adapted(input: &[u64]) -> u64 {
    input
        .iter()
        .copied()
        .filter(|x| x % 2 == 0)
        .map(|x| x.wrapping_mul(x))
        .fold(0u64, |sum, x| sum.wrapping_add(x))
}

Inlining and loop optimization can make the generated code resemble the handwritten version. Whether they do so for a particular program depends on the compiler, target, optimization settings, and surrounding code. We would have to inspect that output and benchmark representative inputs to make a performance claim.fn:19

There is another wrinkle in our request-by-request picture. The standard library can implement a consumer such as fold() by passing the whole accumulation through the adapters. Its Enumerate implementation has specialized fold() and try_fold() methods, so consuming a chain need not literally become a tower of next() calls. The pull model explains the sequence's behavior; optimized bulk operations can implement it differently.fn:4

Some costs are visible without a benchmark. Our simple adapter chain doesn't require an intermediate collection at every step. It uses concrete types instead of a required virtual call at every boundary. Neither fact makes the predicate free, guarantees vectorization, or eliminates allocation in user-supplied code.

In Fast Writes, Fresh Reads, moving work into a background thread introduced replay and coordination costs. Here, calling filter() doesn't start a worker at all. The caller runs the predicate as it consumes the iterator. A fluent chain of methods doesn't, by itself, tell us where computation runs.

Asynchronous iteration and coroutines

The telemetry example starts with a slice already in memory. A live connection has another possibility: there is no new reading yet, but more may arrive.

An ordinary iterator can block inside next() until data arrives. Its interface doesn't say whether a call will return quickly. What it lacks is a way to return "not ready" together with an asynchronous wakeup arrangement.

The Stream trait from futures-core adds that distinction:fn:20

rustThe poll_next signature from futures-core::Stream, with surrounding declarations omitted.Link
fn poll_next(
    self: Pin<&mut Self>,
    cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>>;
Result Meaning
Ready(Some(value)) A value is available
Ready(None) The stream has ended
Pending No value yet; arrange a wakeup when progress may be possible

Context gives the implementation access to a waker. Pin supports implementations whose state must stay at a stable location while pinned. Those requirements serve asynchronous execution, beyond the in-memory loop we started with.fn:21

Rust's async computations use the Future protocol. The compiler represents their progress in a generated state machine, retaining what is needed across an await.fn:22, fn:23

A coroutine lets a function suspend and later resume from where it stopped. A synchronous generator uses that ability to yield values one at a time, with its consumer requesting each resumption.fn:24

When producing a value involves nested loops and several yield points, that can be easier to follow than a hand-written state machine. Our numbering adapter needed only a source and a counter; more complicated control flow can justify the extra mechanism.

There is also a boundary between local demand and system backpressure. A caller can stop pulling this iterator while a device, broker, or network buffer keeps receiving data. The capacity, loss, and admission policies from Backpressure in a Telemetry Pipeline still need to exist outside the iterator. A take() at the end of a chain doesn't bound every queue upstream.

Iterator composition in C++

C++ ranges let us build a similar lazy pipeline, so they give us a way to ask which parts of the design are specific to Rust. C++23 provides enumeration directly:fn:25

cppC++23's standard enumeration view needs no custom coroutine generator.Link
#include <array>
#include <iostream>
#include <ranges>

int main() {
    std::array values{1, 2, 3, 4};

    for (auto [index, value] : std::views::enumerate(values)) {
        std::cout << index << ": " << value << '\n';
    }
}

C++20 ranges already offered lazy composition; C++23 added this standard numbering adapter. Comparing a small Rust enumerate() call with the plumbing of a hand-built C++ coroutine generator would measure two different implementation choices.

C++ ranges use iterator and sentinel interfaces, concepts, and views. A sentinel marks the end condition; it need not have the same type as the iterator. Those interfaces support lazy computation and compiler optimization too. Rust doesn't have exclusive access to that technique.

Both languages support references, moves, and deterministic destruction. Rust's borrowing rules add compiler checks for reference lifetimes and exclusive access across the composition. C++ APIs can express ownership and borrowing relationships, but ordinary references don't generally carry the same static checks. The borrowing example is where I find the comparison most useful: who must establish that these records are still valid when a result is used?

Choosing the mechanism

We can now account for the numbered loop. The source remembers its position. Enumerate remembers a counter. A filter may ask several times before passing a value along. The consumer decides whether to keep asking, and the item type preserves whether the result owns or borrows its data.

For a query over an existing buffer, returning a borrowed iterator lets the caller inspect a few matches without first building a collection. If obtaining the next value requires waiting for a socket, an ordinary iterator can block inside next(). When the caller must yield execution while waiting and resume when progress becomes possible, the interface needs an asynchronous readiness and wakeup protocol. If later work needs to revisit or sort the results, collecting them may be the right choice.

When I read an iterator chain now, I try to picture the state each adapter holds and the work one request can trigger. That gives me a way to judge the abstraction before making assumptions about its speed.

References

[fn:1] Rust standard library. Iterator, required associated type and method, and the contract for next().

[fn:2] The Rust Reference. Iterator loops, including IntoIterator and the complete for desugaring.

[fn:3] Rust standard library. FusedIterator and Iterator::fuse.

[fn:4] Rust standard library. Enumerate source, including stored state and specialized consumers.

[fn:5] Rust standard library. Iterator::enumerate, including its public overflow contract.

[fn:6] Rust standard library. Iterator::scan, an adapter with an initial state and a closure that updates it for each source item.

[fn:7] Rust standard library. Iterator::filter, including its borrowed predicate argument.

[fn:8] Rust standard library. Iterator laziness and Iterator::take.

[fn:9] Rust standard library. The three forms of iteration and Vec.

[fn:10] The Rust Reference. Destructors, recursive destruction of owned fields. Vec::IntoIter source implements destruction of remaining elements.

[fn:11] The Rust Reference. Closure capture by value, including copying and moving captures.

[fn:12] The Rustonomicon. Splitting borrows, including why ordinary Iterator permits retaining several results across calls.

[fn:13] The Rust Reference. Return-position impl Trait, an unnamed concrete type.

[fn:14] The Rust Programming Language. Performance of code using generics. The Rust Compiler Development Guide describes monomorphization and its compilation-time and code-size costs.

[fn:15] The Rust Reference. Trait objects, data pointers, vtables, and runtime method dispatch.

[fn:16] The Rust Programming Language. Performing dynamic dispatch, including specialization and inlining trade-offs.

[fn:17] The Rust Reference. Dyn compatibility, including methods excluded through Self: Sized.

[fn:18] The Rust Reference. Pointer and reference layout. Its current two-usize observation for pointers to dynamically sized types is explicitly not a general layout guarantee.

[fn:19] The Rust Programming Language. Performance in loops vs. iterators. Its measurements illustrate a particular program; they aren't measurements of the functions in this article.

[fn:20] futures-core. Stream, polling outcomes and wakeup requirements.

[fn:21] Rust standard library. Pinning, including address-sensitive state and the Unpin exception.

[fn:22] Rust standard library. Future, polling and wakeups.

[fn:23] The Rust Reference. Async blocks, including their generated state.

[fn:24] C++ working draft. Coroutine definitions, including a generator resumed directly by its consumer.

[fn:25] C++ working draft. Enumerate view, including its stored position and iterator operations. WG21's P2164 tracking record records its adoption for C++23.