简体   繁体   English

为什么我们不从Iterator实现所有函数来实现迭代器?

[英]Why don't we implement all the functions from Iterator to implement an iterator?

To implement an iterator in Rust, we only need to implement the next method, as explained in the documentation . 要在Rust中实现迭代器,我们只需要实现next方法,如文档中所述 However, the Iterator trait has many more methods . 但是, Iterator特性还有更多方法

As far as I know, we need to implement all the methods of a trait. 据我所知,我们需要实现特征的所有方法。 For instance, this does not compile ( playground link ): 例如,这不编译( playground链接 ):

struct SomeStruct {}

trait SomeTrait {
    fn foo(&self);
    fn bar(&self);
}

impl SomeTrait for SomeStruct {
    fn foo(&self) {
        unimplemented!()
    }
}

fn main() {}

The error is pretty clear: 错误很明显:

error[E0046]: not all trait items implemented, missing: `bar`
 --> src/main.rs:8:1
  |
5 |     fn bar(&self);
  |     -------------- `bar` from trait
...
8 | impl SomeTrait for SomeStruct {
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `bar` in implementation

Because every method on Iterator except next has a default implementation . 因为除了next之外的Iterator上的每个方法都有一个默认实现 These are methods implemented in the trait itself, and implementors of the trait gain them "for free": 这些是在特质本身中实现的方法,特征的实现者“免费”获得它们:

struct SomeStruct {}

trait SomeTrait {
    fn foo(&self);

    fn bar(&self) {
        println!("default")
    }
}

impl SomeTrait for SomeStruct {
    fn foo(&self) {
        unimplemented!()
    }
}

fn main() {}

You can tell if a trait method has a default implementation or not through the documentation : 您可以通过文档判断特征方法是否具有默认实现:

Required methods 所需方法

 fn next(&mut self) -> Option<Self::Item> 

Provided methods 提供方法

 fn size_hint(&self) -> (usize, Option<usize>) 

Note that size_hint is in the "provided methods" section — that's the indication that there's a default implementation. 请注意, size_hint位于“提供的方法”部分中 - 这表示存在默认实现。

If you can implement the method in a more efficient way, you are welcome to do so, but note that it is not possible to call the default implementation if you decide to override it . 如果您可以更有效地实现该方法,欢迎您这样做,但请注意, 如果您决定覆盖默认实现,则无法调用默认实现

Specifically for Iterator , it's a great idea to implement size_hint if you can, as that can help optimize methods like collect . 特别是对于Iterator ,如果可以的话,实现size_hint是一个好主意,因为这可以帮助优化像collect这样的方法。

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

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