gpt4 book ai didi

reference - 在引用上泛化迭代器,在值上泛化迭代器

转载 作者:行者123 更新时间:2023-11-29 08:27:43 25 4
gpt4 key购买 nike

我想实现一个特征,其中一个函数将迭代器作为参数,然后对该迭代器作为不可变引用返回的值进行操作。

不过,我也希望我的函数也能处理值的迭代器(无需重复代码)。我该怎么做?

以下不起作用:

impl<T, I: Iterator> FilterItem for SortedFilter<I> where  T: Ord, I::Item: Borrow<T> {
...
}

我明白了

error: the type parameter `T` is not constrained by the impl trait, self type, or predicates

最佳答案

您正在寻找 Borrow特点:

When writing generic code, it is often desirable to abstract over all ways of borrowing data from a given type

use std::borrow::Borrow;

fn print_it<I, T>(iter: I)
where I: Iterator<Item = T>,
T: Borrow<u8>
{
for v in iter {
let a: &u8 = v.borrow();
println!("{}", a);
}
}


fn main() {
let vals = vec![1,2,3];
print_it(vals.iter()); // Iterator of references
print_it(vals.into_iter()); // Iterator of values
}

关于reference - 在引用上泛化迭代器,在值上泛化迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31768556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com