[英]Why don't we implement all the functions from Iterator to implement an iterator?
要在Rust中实现迭代器,我们只需要实现next
方法,如文档中所述 。 但是, Iterator
特性还有更多方法 。
据我所知,我们需要实现特征的所有方法。 例如,这不编译( playground链接 ):
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
上的每个方法都有一个默认实现 。 这些是在特质本身中实现的方法,特征的实现者“免费”获得它们:
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
位于“提供的方法”部分中 - 这表示存在默认实现。
如果您可以更有效地实现该方法,欢迎您这样做,但请注意, 如果您决定覆盖默认实现,则无法调用默认实现 。
特别是对于Iterator
,如果可以的话,实现size_hint
是一个好主意,因为这可以帮助优化像collect
这样的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.