Simplify where clause with repeated associated type restrictions

≡放荡痞女 提交于 2019-12-23 20:07:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!