简体   繁体   English

Iterator特性中的type Item是什么意思

[英]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; DRtype Item; in Iterator is an associated type. Iterator是一个关联的类型。


Rust generics have both Input and Output types: Rust泛型具有输入和输出类型:

  • 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) 输入类型是在特征的声明中指定的类型( trait X<T, U>TU作为输入类型)加上Self (实现特征的具体类型)
  • Output types are those specified in the definition of the trait via type X; 输出类型是特征定义中通过type X;指定的type X;

The RFC that introduced associated items is RFC 195: Associated Items . 引入关联项目的RFCRFC 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. 对我而言,最重要的一点是统一性 :为该特性的任何给定实现定义了一个单一类型,例如,它可以为DerefIndex特性提供清洁动力。 In a world where Deref or Index could yield many possible types, type inference would be even more complicated. DerefIndex可以产生许多可能的类型的世界中,类型推断会更加复杂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM