Vec
,我希望输出收集类型也是
Vec
。
fn clone_if<'a, List, ItemType, BinaryPredicate>(list: List, binary_predicate: BinaryPredicate) -> List
where
List: Clone + IntoIterator<Item = &'a ItemType> + Copy,
ItemType: 'a,
BinaryPredicate: Fn(&ItemType) -> bool
{
let mut res = list.clone();
for item in res.into_iter() {
if !binary_predicate(&item) {
// res.remove();
}
}
res
}
fn main() {
let first_list = vec![1, 2, 3, 4, 5, 6];
let second_list = clone_if(&first_list, |item| {
(item & 1) == 0
});
assert_eq!(vec![2, 4, 6], *second_list);
}
当前功能'
clone_if
与您想要实现的目标不兼容。因此,我将其稍微重写以匹配您真正想要的东西。您去的地方:
fn clone_if<List, ItemType, BinaryPredicate>(list: &List, binary_predicate: BinaryPredicate) -> List
where
for<'a> &'a List: IntoIterator<Item = &'a ItemType>,
List: FromIterator<ItemType>,
ItemType: Clone,
BinaryPredicate: Fn(&ItemType) -> bool,
{
list.into_iter()
.filter(|val| binary_predicate(*val))
.cloned()
.collect()
}
fn main() {
let first_list = vec![1, 2, 3, 4, 5, 6];
let second_list = clone_if(&first_list, |item| (item & 1) == 0);
assert_eq!(vec![2, 4, 6], *second_list);
}
解释:
list: &List
-要以您在main
中的方式称呼它,您需要在此处参考。
for<'a> &'a List: IntoIterator<Item = &'a ItemType>
list
参考在迭代时产生对其元素的引用,这与兼容。这样可以防止不必要的复制。
&Vec
List: FromIterator<ItemType>
。
collect()
-您想在输出列表中创建输入项目的克隆由于不必要,因此将所有其他
ItemType: Clone
和Clone
then算法本身:
Copy
.into_iter()
Iterator<Item = &ItemType>
-进行过滤。尚未制作副本。需要关闭和解雇的原因是因为
.filter(|val| binary_predicate(*val))
对迭代的项目进行了参考,在这种情况下,这将是
filter
&&ItemType
转换为
&&ItemType
&ItemType
的需求。
binary_predicate
-克隆所有迭代的项目。这将转换为.cloned()
Iterator<Item = &ItemType>
使用
Iterator<Item = ItemType>
将
filter()
转换为
.collect()
。