3
votes

The Iterator trait is defined as follows:

pub trait Iterator {
    type Item;
    fn next(&mut self) -> Option<Self::Item>;
}

What does type Item; mean? And how to call it?

Is the definition above equivalent to this one?

pub trait Iterator<T> {
    fn next(&mut self) -> Option<T>;
}

If it's the same why declare it that way? And if it's not the same then what's the difference?

1
And if it's not the same then what's the difference?When is it appropriate to use an associated type versus a generic type?Shepmaster

1 Answers

5
votes

TL;DR: The type Item; in Iterator is an associated type.


Rust generics have both Input and Output types:

  • Input types are those specified in the declaration of the trait (trait X<T, U> has T and U as input types) plus Self (the concrete type for which the trait is being implemented)
  • Output types are those specified in the definition of the trait via type X;

The RFC that introduced associated items is RFC 195: Associated Items. Specifically, its motivation section cites the benefits of having associated traits.

For me, the most important point is unicity: a single type is defined for any given implementation of the trait, which allows cleanly powering the Deref or Index trait for example. In a world where Deref or Index could yield many possible types, type inference would be even more complicated.