我们为什么不实现Iterator的所有功能来实现迭代器? [英] Why don't we implement all the functions from Iterator to implement an iterator?

查看:58
本文介绍了我们为什么不实现Iterator的所有功能来实现迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要在Rust中实现迭代器,我们只需实现next方法,如文档中的内容.但是,Iterator特征还有很多方法.

To implement an iterator in Rust, we only need to implement the next method, as explained in the documentation. However, the Iterator trait has many more methods.

据我所知,我们需要实现特征的所有方法.例如,它不会编译(游乐场链接):

As far as I know, we need to implement all the methods of a trait. For instance, this does not compile (playground link):

struct SomeStruct {}

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

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

fn main() {}

错误非常明显:

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

推荐答案

因为除next之外的Iterator上的每个方法都具有

Because every method on Iterator except next has a default implementation. 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() {}

您可以通过文档:

必需的方法

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

提供的方法

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

请注意,size_hint在提供的方法"部分中-这表明存在默认实现.

Note that size_hint is in the "provided methods" section — that's the indication that there's a default implementation.

如果您可以更有效的方式实现该方法,欢迎您这样做,但是请注意,它是

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.

专门针对Iterator,如果可以的话,最好实现size_hint,因为这可以帮助优化collect之类的方法.

Specifically for Iterator, it's a great idea to implement size_hint if you can, as that can help optimize methods like collect.

这篇关于我们为什么不实现Iterator的所有功能来实现迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆