I wrote the following function to sum over an iterator:
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)
}
This compiles fine with Rust 1.0.0, but it would be nice if one could avoid repeating I::Item
four times and instead refer to a type T
and say somewhere that Iterator::Item = T
only once. What's the right way to do this?
You can add
T
as a type parameter for your function, and requireI
to implementIterator<Item = T>
, like this: