skip to content

In Rust, what does `fn skus(&self) -> impl Iterator<Item = u32>` in a trait declaration mean for implementors, generic callers and `dyn` use of that trait?

level: seniorimportance: nice to knowfreq 25%

answer

  1. an anonymous associated type
  2. each impl picks its own
  3. generic code sees declared bounds
  4. not dispatchable through dyn

basics

~20 s

Since Rust 1.75, impl Trait in a trait method's return is an anonymous associated type: each impl picks its own hidden type, generic callers see only the declared bounds, and the method blocks dyn use (E0038).

solid answer

~40 s

Return-position `impl Trait` in traits, stable since Rust 1.75, desugars to an anonymous associated type. Each implementation chooses its own hidden type, so one impl can return an adapter over a `Vec` and another a range. Code generic over `I: Inventory` sees only the trait's bounds: passing `i.skus()` where `Send` is required fails with E0277 unless the trait declares `+ Send`. Because each impl returns a different type, the method cannot go in a vtable, and `dyn Inventory` fails with E0038; `where Self: Sized` on the method restores dyn compatibility by leaving it off the vtable. An impl may write its concrete type instead, which rustc accepts with the `refining_impl_trait` warning.

code

rust · 34 lines
rust
trait Inventory {
    fn skus(&self) -> impl Iterator<Item = u32>;
}

struct Shelf {
    items: Vec<u32>,
}

struct Range {
    start: u32,
    end: u32,
}

impl Inventory for Shelf {
    fn skus(&self) -> impl Iterator<Item = u32> {
        self.items.iter().copied()
    }
}

impl Inventory for Range {
    fn skus(&self) -> impl Iterator<Item = u32> {
        self.start..self.end
    }
}

fn count_all(stock: &impl Inventory) -> usize {
    stock.skus().count()
}

fn main() {
    let shelf = Shelf { items: vec![4, 8, 15] };
    let range = Range { start: 100, end: 105 };
    println!("{} {}", count_all(&shelf), count_all(&range));
}

go deeper

for a junior

Recall that since Rust 1.75 a trait method may return impl Trait, and that each type implementing the trait returns its own iterator type.

for a middle

Explain the desugaring to an anonymous associated type and why generic callers see only the declared bounds.

for a senior

Diagnose E0038 and the generic E0277 on Send, and fix them with where Self: Sized, a boxed variant or a + Send bound in the trait.

for a principal

Decide what a public trait promises: a + Send bound or a boxed method is a contract for all future implementors, while leaving it out limits generic callers.

## What the declaration means Since **Rust 1.75** a trait method may return `impl Trait`, often abbreviated **RPITIT** (return-position `impl Trait` in traits): ```rust trait Inventory { fn skus(&self) -> impl Iterator<Item = u32>; } ``` The Rust Reference describes the desugaring: each `impl Trait` in a trait method's return type becomes an **anonymous associated type** of the trait, and each implementation's own return type supplies its value. Before 1.75 the same design needed an explicitly named associated type (`type Skus: Iterator<Item = u32>;`), whose value each impl must write out in full (impossible when it contains a closure type), or a boxed `Box<dyn Iterator<Item = u32> + '_>`, which allocates. ## Implementors Each `impl` chooses **its own** hidden type, just as each impl chooses its own value for an associated type. A `Shelf` can return `self.items.iter().copied()` while a `Range` returns `self.start..self.end`; within one impl the usual rule holds, one concrete type per method. An implementation may also write the **concrete type** instead of `impl Trait`, for example `fn skus(&self) -> std::vec::IntoIter<u32>`. rustc 1.99 accepts that "refinement" with the warning "impl trait in impl method signature does not match trait method signature" from the `refining_impl_trait` lint group, because callers who use `Shelf` directly then see `IntoIter<u32>` and can call `len()` on it, which makes the concrete type part of that type's API. ## Generic callers Code that is generic over `I: Inventory` sees **only the bounds the trait declares**. `i.skus()` is an `Iterator<Item = u32>` and nothing more: - passing it to a function that requires `Send` fails with **E0277**, "`impl Iterator<Item = u32>` cannot be sent between threads safely", even if every existing impl returns a `Send` type; - a concrete caller holding a `Shelf` does see the auto traits of `Shelf`'s hidden type, so the same call compiles there; - the fix is to put the promise in the trait: `fn skus(&self) -> impl Iterator<Item = u32> + Send;`. Every impl must then satisfy it. Lifetimes are generous here in every edition: a return-position `impl Trait` in a trait method captures all in-scope generic parameters, `Self` and the `&self` lifetime included, so the returned iterator may borrow from `self`. ## `dyn Inventory` A method returning `impl Trait` is **not dispatchable** through a trait object, because every implementation returns a differently sized, different type and no single vtable entry can describe them. The Reference lists "not have a return position impl Trait type" among the requirements for dispatchable methods. Writing `Vec<Box<dyn Inventory>>` fails with **E0038**, "the trait `Inventory` is not dyn compatible", and the note "...because method `skus` references an `impl Trait` type in its return type". Ways out: 1. Add `where Self: Sized` to the method. The trait becomes dyn-compatible again, the method stays callable on concrete types, and it is simply absent from `dyn Inventory`. 2. Offer a boxed variant, such as a separate method returning `Box<dyn Iterator<Item = u32> + '_>`, for callers that need dynamic dispatch. 3. Keep the trait static-dispatch only, if no caller needs a heterogeneous collection. ## Choosing a return shape for a trait method 1. **`impl Trait` in the method** when implementors' types are unnameable or private and callers use the trait through generics. 2. **A named associated type** when callers must name or bound the type, for example `where I::Skus: Clone`, or store it in a struct. 3. **`Box<dyn Iterator<Item = u32> + '_>`** when the trait must be used as `dyn Inventory` and the method must stay dispatchable; it costs one allocation per call. ## Summary | Who | Sees | |---|---| | An implementor | its own hidden type, chosen per impl | | A caller with a concrete type | that impl's hidden type behind the opaque type, including its auto traits | | A caller generic over `I: Inventory` | only the bounds written in the trait | | A `dyn Inventory` user | nothing: the method is not dispatchable, E0038 unless `where Self: Sized` |

  • In Rust, how do you keep `skus` returning `impl Iterator` and still build a `Vec<Box<dyn Inventory>>`?
    Add `where Self: Sized` to `skus` in the trait. The Reference treats such a method as explicitly non-dispatchable, so the trait becomes dyn-compatible again: `dyn Inventory` exposes the other methods, while `skus` stays callable on concrete types such as `Shelf`. If dyn users also need the items, add a separate method returning `Box<dyn Iterator<Item = u32> + '_>`.
  • In Rust, why does generic code fail to send `i.skus()` to another thread when every impl returns a `Send` iterator?
    Generic code is checked against the trait, not against today's impls. The trait promises only `Iterator<Item = u32>`, so for an arbitrary `I: Inventory` the compiler cannot assume `Send` and reports E0277. Declaring `-> impl Iterator<Item = u32> + Send` in the trait makes it a requirement on every impl and a guarantee for every caller.

  • All implementors of the trait must return the same concrete iterator type
  • Generic callers can rely on Send when every current impl returns a Send type
  • A trait method returning impl Trait can still be called through dyn Trait
  • An impl must repeat impl Trait and may never write its concrete type
  • impl Trait in trait methods is still a nightly-only feature

Assumes Rust 1.99; return-position impl Trait in trait methods has been stable since Rust 1.75 (December 2023), and earlier code used named associated types or boxed iterators.