当我骑自行车时
fn main() {
let mut a = vec![1,2].into_iter().cycle();
assert_eq!(a.next().unwrap(), 1);
assert_eq!(a.next().unwrap(), 2);
assert_eq!(a.next().unwrap(), 1);
assert_eq!(a.next().unwrap(), 2);
}就像我所期望的那样运作良好。但是当我试图把广义函数写成
pub fn cycle_generalized_func<T>(into_iter: T) -> impl Iterator<Item = T::Item>
where
T: IntoIterator,
T::Item: Clone,
{
into_iter.into_iter().cycle()
}试着用它
let mut a = cycle(vec![1,2]);id不会使into_iter.into_iter().cycle()行复杂并产生错误,如下所示:
特性绑定
<T as IntoIterator>::IntoIter: Clone不满足特性Clone未为<T as IntoIterator>::IntoIterrustcE0277 iterator.rs(3270,23)实现:std::iter::Iterator::cyclemain.rs(6,19)中的绑定所需:考虑进一步限制关联类型:, <T as IntoIterator>::IntoIter: Clone
我做错什么了?我不知道怎么修理它
发布于 2022-11-05 07:49:13
Iterator::cycle的类型是:
fn cycle(self) -> Cycle<Self>ⓘ
where
Self: Clone也就是说,它要求迭代器本身是: Clone,而不是Item。若要修复代码,请将T::Item: Clone替换为T::IntoIter: Clone。
这是为我汇编的:
pub fn cycle_generalized_func<T>(into_iter: T) -> impl Iterator<Item = T::Item>
where
T: IntoIterator,
T::IntoIter: Clone,
{
into_iter.into_iter().cycle()
}如果您需要它来处理不是Clone的迭代器,但是条目是这样的,那么您必须首先将所有条目收集到像Vec这样的容器中:
pub fn cycle_generalized_func<T>(into_iter: T) -> impl Iterator<Item = T::Item>
where
T: IntoIterator,
T::Item: Clone,
{
into_iter
.into_iter()
.collect::<Vec<_>>()
.into_iter()
.cycle()
}https://stackoverflow.com/questions/74325975
复制相似问题