3

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Mateo
  • 1,494
  • 1
  • 18
  • 27

1 Answers1

4

You can add T as a type parameter for your function, and require I to implement Iterator<Item = T>, like this:

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)
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Levans
  • 14,196
  • 3
  • 49
  • 53