为什么`FromIterator`的实现使用`IntoIterator`而不是`Iterator`? [英] Why does the implementation of `FromIterator` use an `IntoIterator` instead of an `Iterator`?
问题描述
The example implementation of the FromIterator
trait in the Rust docs is:
impl FromIterator<i32> for MyCollection {
fn from_iter<I: IntoIterator<Item=i32>>(iter: I) -> Self {
let mut c = MyCollection::new();
for i in iter {
c.add(i);
}
c
}
}
FromIterator
定义如何从迭代器创建类型. from_iter
的签名需要一个实现IntoIterator
的类型,该类型定义了如何将类型转换为Iterator
.
FromIterator
defines how a type will be created from an iterator. The signature of from_iter
requires a type that implements IntoIterator
, which defines how a type may be converted into an Iterator
.
from_iter
是这样定义的,因为IntoIterator
的要求不像Iterator
一样严格吗?
Is from_iter
defined this way because IntoIterator
is not as strict a requirement as Iterator
?
推荐答案
from_iter
是这样定义的,因为IntoIterator
的要求不像Iterator
一样严格吗?
Is
from_iter
defined this way becauseIntoIterator
is not as strict a requirement asIterator
?
是的
IntoIterator
是为Iterator
自动实现的,因此实现IntoIterator
的类型集是实现Iterator
的那些类型的超集.
IntoIterator
is automatically implemented for Iterator
, therefore the set of types implementing IntoIterator
is a superset of those implementing Iterator
.
制作通用函数时,最好将其需求降到最低,即,使其尽可能通用.
When crafting a generic function, it's good to minimize its requirements, i.e., make it as generic as possible.
当然,需要在以下两者之间进行权衡:
Of course, there's a trade-off between:
- 易用性:适用于尽可能多的类型,
- 易于实施.
- ease of use: works with as many types as possible,
- ease of implementation.
对于孤立代码库中的一个单独功能,可能不值得在易用性上进行大量优化.对于标准库中的特征/功能,由于用户数量远远超过了(此特定产品的)开发人员的数量,因此,折衷方案强烈支持易用性.
For a lone function in your isolated codebase, it may not be worth optimizing for ease-of-use much; for a trait/function in the standard library, since the number of users far outweigh the number of developers (of this particular piece), the trade-off is strongly in favor of ease-of-use.
由于从IntoIterator
转到Iterator
非常简单,因此对实现没有太大影响,因此很容易进行调用.
And since going from IntoIterator
to Iterator
is so simple, and thus doesn't weigh much on the implementation, it's an easy call to make.
这篇关于为什么`FromIterator`的实现使用`IntoIterator`而不是`Iterator`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!