skip to content

As a Rust library lead, what rule do you set for public functions that return iterators: `impl Iterator`, a named iterator type, or `Box<dyn Iterator>`?

level: principalimportance: should knowfreq 30%

answer

  1. impl Trait: zero-cost, but unnameable
  2. named struct: callers can store and clone it
  3. std returns str::Lines, not impl Iterator
  4. Box<dyn>: allocation plus dynamic dispatch
  5. an opaque type promises only its listed traits

basics

~20 s

Inside an application, return impl Iterator: it is zero-cost and the code is easy to change. In a library's public API, prefer a named iterator struct when callers may store, clone or name the result, as std does with str::Lines. Use Box<dyn Iterator> only when one signature must return different types at run time.

solid answer

~60 s

The three options trade cost against what callers can do. `impl Iterator<Item = T>` is free at run time and lets me change the adapter chain later, but callers see only `Iterator`: they cannot name the type, so storing it in their own struct forces them to add a generic parameter, and they cannot call `clone` or `next_back` unless I list those traits in the signature. A named struct such as `pub struct Evens<'a>` costs a few lines of `impl Iterator`, but callers can name it, keep it in a field and use every trait I implement, and the struct's traits are my documented promise; std makes that choice, so `str::lines` returns `Lines<'_>`, which derives `Clone` and implements `DoubleEndedIterator`. `Box<dyn Iterator<Item = T>>` is nameable and flexible but allocates on every call and dispatches through a vtable, so I reserve it for returns whose concrete type varies at run time or for dyn-compatible trait methods. My rule: `impl Iterator` for internal and application code, a named type for library APIs whose results callers keep, and `Box<dyn>` only with a reason in review.

code

rust · 35 lines
rust
// A named iterator type: callers can name it, store it and clone it.
#[derive(Clone)]
pub struct Evens<'a> {
    inner: std::slice::Iter<'a, u32>,
}

impl<'a> Iterator for Evens<'a> {
    type Item = &'a u32;
    fn next(&mut self) -> Option<&'a u32> {
        self.inner.by_ref().find(|n| *n % 2 == 0)
    }
}

pub fn evens(v: &[u32]) -> Evens<'_> {
    Evens { inner: v.iter() }
}

// The opaque version: zero-cost, but the caller sees only `Iterator`.
pub fn evens_opaque(v: &[u32]) -> impl Iterator<Item = &u32> {
    v.iter().filter(|n| *n % 2 == 0)
}

// Storing the named type needs no generic parameter and no Box.
struct Cursor<'a> {
    pending: Evens<'a>,
}

fn main() {
    let data = [1, 2, 3, 4, 6];
    let mut c = Cursor { pending: evens(&data) };
    let snapshot = c.pending.clone(); // Clone is part of the named type's promise
    println!("{:?}", c.pending.next());
    println!("{:?}", snapshot.collect::<Vec<_>>());
    println!("{:?}", evens_opaque(&data).count());
}

go deeper

for a junior

Know that impl Iterator returns an iterator without naming its type and that callers can only use Iterator's methods on it.

for a middle

Explain the difference between an opaque return type, a named iterator struct and Box<dyn Iterator> in cost and in what callers can do.

for a senior

Choose the return type for a concrete API, list the traits an opaque type must promise, and check what it captures on edition 2024.

for a principal

Set the team's rule per kind of API and treat every promised trait as a compatibility commitment, using std's named iterators as the model.

## Three ways to hand back an iterator A function that filters or maps a collection produces an adapter type such as `Filter<Iter<'_, u32>, {closure}>`, which nobody can write out because the closure's type has no name. Rust offers three ways to return it, and the choice decides what callers may do with the result. | Return type | Run-time cost | Caller can name or store it | Traits the caller can use | |---|---|---|---| | `impl Iterator<Item = T>` | none | not by name; storing it needs a generic | only those written in the signature | | named struct, `Evens<'a>` | none | yes, as a plain field | every trait the struct implements | | `Box<dyn Iterator<Item = T>>` | one allocation per call, indirect calls | yes | `Iterator` (plus listed auto traits) | ## What an opaque type does and does not promise `impl Iterator<Item = &u32>` hides the concrete type, which is the point: the library can switch from `filter` to `filter_map` or to a hand-written loop without touching callers. The cost is on the caller's side: - **No name.** A caller who wants to keep the iterator in a struct cannot write its type, so the struct must take a type parameter or box the value. - **Only the listed traits.** The opaque type exposes `Iterator` and nothing else, so `it.clone()` fails with E0599 even though the hidden adapter implements `Clone`. Promising more means writing `impl Iterator<Item = &u32> + Clone`, and that promise is then as binding as a named type's. - **Captured lifetimes.** On edition 2024 a return-position `impl Trait` captures every in-scope lifetime unless narrowed with `use<..>`, so a public signature should be checked for what it borrows. ## Why std returns named types The standard library almost never returns `impl Iterator` from a stable public method. `str::lines` returns `std::str::Lines<'_>`, `slice::iter` returns `std::slice::Iter<'_, T>`, and so on. Each struct derives or implements the traits std is willing to promise, such as `Clone`, `Debug` and `DoubleEndedIterator` for `Lines`, and callers can store the iterator in a field, put it in a type alias or implement their own traits on top of it. The library pays a few lines of boilerplate and gains a type it can document and evolve by adding trait impls. ## When the box is right `Box<dyn Iterator<Item = T>>` is the answer when the concrete type genuinely varies at run time, for example a function that returns either a filtered iterator or an empty one depending on input, or a method on a trait that must stay dyn compatible, where return-position `impl Trait` is not allowed for trait objects. The price is a heap allocation per call and a vtable call per item, which matters in hot loops and rarely elsewhere. ## A rule the team can apply 1. **Application and internal code: `impl Iterator`.** It is zero-cost and keeps refactoring cheap; nobody outside the crate stores the type. 2. **Library APIs whose results callers keep: a named struct.** Implement `Iterator` and the traits you are willing to promise, and document them; adding a trait later is compatible, removing one is not. 3. **If you return `impl Trait` publicly, list the traits callers need** (`+ Clone`, `+ DoubleEndedIterator`) and check the captured lifetimes, because both are part of the contract. 4. **`Box<dyn Iterator>` only with a reason:** run-time variation of the concrete type or dyn compatibility. 5. **Benchmark before boxing in hot paths,** since the allocation and indirect calls are the cost the other two options avoid. ## How to frame it in an interview Name the audience first: who receives the iterator and what they will do with it. Then the trade: `impl Trait` hides the type for free, a named type exposes a documented one for a little code, and a box buys run-time flexibility with an allocation. A lead's contribution is the default per kind of API and the habit of treating every listed trait as a promise.

  • Is changing a public function from `impl Iterator` to a named struct a breaking change?
    Usually not for callers, because the named type still implements `Iterator` and every trait the opaque signature listed, so code that only iterated keeps compiling. The reverse direction, from a named type to `impl Iterator`, breaks any caller that named the type or used a trait the opaque signature does not list.
  • Why not return `Vec<T>` and avoid the question?
    A `Vec` forces the whole result to be computed and allocated up front, even when the caller wants only the first item or will stop early. Returning an iterator keeps the work lazy and lets the caller choose to collect; a `Vec` is right when the caller will always need every element or the data must outlive its source.

  • impl Iterator in a public signature lets callers use every trait the hidden type implements.
  • Box<dyn Iterator> is free because the compiler removes the allocation.
  • Named iterator structs are an old style that impl Trait made obsolete.
  • Callers can store an impl Iterator in a struct field by writing impl Iterator as the field type.