[英]What does `type Item` in the `Iterator` trait mean
The Iterator
trait is defined as follows: Iterator
特征定义如下:
pub trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}
What does type Item;
什么
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;
TL; DR :
type Item;
in Iterator
is an associated type. 在
Iterator
是一个关联的类型。
Rust generics have both Input and Output types: Rust泛型具有输入和输出类型:
trait X<T, U>
has T
and U
as input types) plus Self
(the concrete type for which the trait is being implemented) trait X<T, U>
以T
和U
作为输入类型)加上Self
(实现特征的具体类型) type X;
type X;
指定的type X;
The RFC that introduced associated items is RFC 195: Associated Items . 引入关联项目的RFC是RFC 195:关联项目 。 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. 对我而言,最重要的一点是统一性 :为该特性的任何给定实现定义了一个单一类型,例如,它可以为
Deref
或Index
特性提供清洁动力。 In a world where Deref
or Index
could yield many possible types, type inference would be even more complicated. 在
Deref
或Index
可以产生许多可能的类型的世界中,类型推断会更加复杂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.