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

标签 iterator rust traits

要在 Rust 中实现迭代器,我们只需要实现 next 方法,如 in the documentation 所解释的那样.但是,Iterator 特征 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

最佳答案

因为 Iterator 上的每个方法除了 next有一个default implementation .这些是在特征本身中实现的方法,特征的实现者“免费”获得它们:

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位于“提供的方法”部分 — 这表明存在默认实现。

如果你能以更高效的方式实现该方法,欢迎你这样做,但请注意它是not possible to call the default implementation if you decide to override it .

专用于Iterator , 实现 size_hint 是个好主意如果可以的话,因为这可以帮助优化像 collect 这样的方法.

关于iterator - 为什么我们不实现 Iterator 中的所有函数来实现一个迭代器呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40516692/

相关文章:

c++ - move_iterator 对于返回纯右值的迭代器被破坏并返回悬空引用

c++ - 遍历字符串 vector ,从控制台获取输入,给出段错误

php - 如何在 PHP 中正确安全地委托(delegate)迭代器?

rust - 获取枚举的底层变量

scala - 使用密封特征作为 map 的键

rust - rust 说特质From <i32>未实现

C++ 二进制文件和迭代器 : getting away with a 1:1 using ifstreambuf_iterator?

types - 我如何在 Rust 中获得 `std::any::TypeId::of` 超过 `T` 、 `&T` 和 `&mut` T 的相同结果?

rust - Once_cell的异步版本,或者避免错误的方法[E0744] : `.await` is not allowed in a `static` ?

rust - 有没有办法继承一个特征以使用该特征的所有方法?