【问题标题】:Why don't we implement all the functions from Iterator to implement an iterator?为什么我们不实现 Iterator 的所有功能来实现一个迭代器呢?
【发布时间】:2017-03-23 20:05:37
【问题描述】:

要在 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 rust traits


    【解决方案1】:

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

    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方法是否有默认实现:

    必需的方法

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

    提供的方法

    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 等方法。

    【讨论】:

    • 真的很好!我最近正在复制粘贴一些代码,并认为有一种方法可以为方法提供默认实现会很好。我只是假设没有继承这是不可能的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    • 2013-05-31
    • 2020-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多