为什么我们不实现 Iterator 中的所有函数来实现一个迭代器呢?

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

要在 Rust 中实现迭代器,我们只需要实现 next 方法,如 in the documentation. However, the Iterator trait has many more methods 所述。

据我所知,我们需要实现一个trait的所有方法。例如,这不会编译 (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 上的每个方法都有一个 default implementation。这些是在特征本身中实现的方法,特征的实现者获得它们 "for free":

struct SomeStruct {}

trait SomeTrait {
    fn foo(&self);

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

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

fn main() {}

你可以通过the documentation:

判断一个trait方法是否有默认实现

Required methods

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

Provided methods

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

请注意 size_hint 在 "provided methods" 部分中 — 这表明存在默认实现。

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

特别是 Iterator,如果可以的话,实现 size_hint 是个好主意,因为这可以帮助优化像 collect.

这样的方法