gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:24:32 28 4
gpt4 key购买 nike

自关联类型 IntoIterIntoIterator trait,实现了 Iterator trait,这不足以推断关联类型 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"]);
}

关于rust - 为什么 IntoIterator trait 需要显式指定关联类型 Item?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65453790/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com