问题
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)
}
来源:https://stackoverflow.com/questions/29462526/simplify-where-clause-with-repeated-associated-type-restrictions