为什么 IntoIterator trait 需要显式指定关联类型 Item?

Why does the IntoIterator trait require explicitly specifying the associated type Item?

由于 IntoIterator 特征的关联类型 IntoIter 实现了 Iterator 特征,是否足以推断出关联类型 Item

Why does the IntoIterator trait require explicit type Item declaration?

不会。你是对的,当你 impl IntoIterator for ... 然后 Item 冗余 ,并且 可以 通过 IntoIter 获得.


这是在 PR #22313 中引入的。简而言之,引入的原因是为了简化 where 子句。如果您必须指定 IntoIter 那么这很快就会变得很麻烦。

where I: IntoIterator<IntoIter = ...>

那样的话就容易多了:

where I: IntoIterator<Item = ...>

让我们考虑一个随机的例子,比如 print_strings。然后在你需要做这样的事情之前:

fn print_strings<I, T>(iter: I)
where
    I: IntoIterator<IntoIter = T>,
    T: Iterator<Item = &'static str>,
{
    for s in iter {
        println!("{}", s);
    }
}

而现在可以简化为:

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"]);
}