我编写了以下函数来对迭代器求和:
use std::ops::Add;
fn sum_iter<I>(s: I, init: &I::Item) -> I::Item
where
I: Iterator + Clone,
<I as Iterator>::Item: Add<I::Item, Output = I::Item> + Copy,
{
s.clone().fold(*init, |acc, item| acc + item)
}
这在 Rust 1.0.0 上编译得很好,但如果可以避免重复 I::Item
四次而是引用类型 T
和在某个地方说 Iterator::Item = T
只有一次。执行此操作的正确方法是什么?
最佳答案
您可以添加 T
作为函数的类型参数,并需要 I
实现Iterator<Item = T>
,像这样:
fn sum_iter<I, T>(s: I, init: &T) -> T
where
I: Iterator<Item = T> + Clone,
T: Add<T, Output = T> + Copy,
{
s.clone().fold(*init, |acc, item| acc + item)
}
关于generics - 简化具有重复关联类型限制的 where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29462526/