Simplify where clause with repeated associated typ

2019-07-23 09:28发布

问题:

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?

回答1:

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)
}