[英]Why does the IntoIterator trait require explicitly specifying the associated type Item?
Since the associated type IntoIter
of the IntoIterator
trait, implements the Iterator
trait, isn't that sufficient to infer the associated type Item
?由于
IntoIterator
特征的关联类型IntoIter
实现了Iterator
特征,这还不足以推断关联类型Item
吗?
Why does the
IntoIterator
trait require explicittype Item
declaration?为什么
IntoIterator
特征需要显式type Item
声明?
It doesn't .它没有。 You are correct that when you
impl IntoIterator for...
then Item
is redundant , and could be obtained through IntoIter
.你是对的,当你
impl IntoIterator for...
那么Item
是多余的,可以通过IntoIter
获得。
This was introduced in PR #22313 .这是在PR #22313中介绍的。 In short, the reason is was introduced was to simplify where clauses.
简而言之,引入的原因是为了简化 where 子句。 If you have to specify
IntoIter
then that can quickly become cumbersome.如果您必须指定
IntoIter
,那么这很快就会变得很麻烦。
where I: IntoIterator<IntoIter = ...>
In that case it is much easier to do:在这种情况下,这样做要容易得多:
where I: IntoIterator<Item = ...>
Let's consider a random example, like print_strings
.让我们考虑一个随机的例子,比如
print_strings
。 Then before you needed to do something like this:然后在你需要做这样的事情之前:
fn print_strings<I, T>(iter: I)
where
I: IntoIterator<IntoIter = T>,
T: Iterator<Item = &'static str>,
{
for s in iter {
println!("{}", s);
}
}
Whereas now that can be simplified to just:而现在可以简化为:
fn print_strings<I>(iter: I)
where
I: IntoIterator<Item = &'static str>,
{
for s in iter {
println!("{}", s);
}
}
fn main() {
print_strings(vec!["foo", "bar", "baz"]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.