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?
TL;DR : The type Item;
in Iterator
is an associated type.
Rust generics have both Input and Output types:
trait X<T, U>
has T
and U
as input types) plus Self
(the concrete type for which the trait is being implemented) 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.