用重复的关联类型限制简化where子句 [英] Simplify where clause with repeated associated type restrictions
本文介绍了用重复的关联类型限制简化where子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
pre $ sum_iter< I>(s:I,init: & I :: Item) - > I :: Item
其中I:Iterator + Clone,< I as Iterator> :: Item:Add< I :: Item,Output = I :: Item> +复制{
s.clone()。fold(* init,| acc,item | acc + item)
}
这可以在rustc-1.0.0-beta下编译,但如果可以避免重复 I :: Item
四次,而是指一个类型 T
,并说 Iterator :: Item = T 只有一次。什么是正确的做法?
解决方案
是的,您可以简单地添加 T
作为函数的类型参数,并且需要 I
来实现 Iterator< Item = T>
,就像这个:
fn sum_iter< I,T>(s:I,init:& T) - > T
其中I:迭代器< Item = T> +克隆,
T:添加< T,输出= T> +复制
{
s.clone()。fold(* init,| acc,item | acc + item)
}
I wrote the following function to sum over an iterator:
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 under rustc-1.0.0-beta, 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?
解决方案
Yes, you can simply 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)
}
这篇关于用重复的关联类型限制简化where子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文