问题描述
要在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.
如果您可以更有效的方式实现该方法,欢迎您这样做,但是请注意,它是.
专门针对Iterator
,如果可以的话,最好实现size_hint
,因为这可以帮助优化collect
之类的方法.
这篇关于我们为什么不实现Iterator的所有功能来实现迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!