首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何对锈蚀中可迭代类型的唯一性进行具体的过滤?

如何对锈蚀中可迭代类型的唯一性进行具体的过滤?
EN

Stack Overflow用户
提问于 2022-09-23 04:37:28
回答 1查看 51关注 0票数 1

假设我有一个向量向量vec_of_vecs = vec![vec![1,2],vec![1,3],vec![2,2],vec![2,3]]。过滤掉vec![2,2]的惯用方法是什么?

我的尝试是:

代码语言:javascript
复制
fn filter_out_duplicates(vec_of_vecs: Vec<Vec<u8>>) -> Vec<Vec<u8>> {
  vec_of_vecs
     .into_iter()
     .filter(all_unique)
     .collect()
}

pub fn all_unique<T>(iterable: T) -> bool
where
   T: IntoIterator,
   T::Item: Eq + Hash,
{
   let mut unique = HashSet::new();
   iterable.into_iter().all(|x| unique.insert(x))
}

但是这给了我一个错误信息,我很难解码这个错误

代码语言:javascript
复制
the method `collect` exists for struct `std::iter::Filter<std::vec::IntoIter<std::vec::Vec<u8>>, fn(&std::vec::Vec<u8>) -> bool {all_unique::<&std::vec::Vec<u8>>}>`, but its trait bounds were not satisfied
the following trait bounds were not satisfied:
`<fn(&std::vec::Vec<u8>) -> bool {all_unique::<&std::vec::Vec<u8>>} as std::ops::FnOnce<(&std::vec::Vec<u8>,)>>::Output = bool`
which is required by `std::iter::Filter<std::vec::IntoIter<std::vec::Vec<u8>>, fn(&std::vec::Vec<u8>) -> bool {all_unique::<&std::vec::Vec<u8>>}>: std::iter::Iterator`
`fn(&std::vec::Vec<u8>) -> bool {all_unique::<&std::vec::Vec<u8>>}: std::ops::FnMut<(&std::vec::Vec<u8>,)>`
which is required by `std::iter::Filter<std::vec::IntoIter<std::vec::Vec<u8>>, fn(&std::vec::Vec<u8>) -> bool {all_unique::<&std::vec::Vec<u8>>}>: std::iter::Iterator`
`std::iter::Filter<std::vec::IntoIter<std::vec::Vec<u8>>, fn(&std::vec::Vec<u8>) -> bool {all_unique::<&std::vec::Vec<u8>>}>: std::iter::Iterator`
which is required by `&mut std::iter::Filter<std::vec::IntoIter<std::vec::Vec<u8>>, fn(&std::vec::Vec<u8>) -> bool {all_unique::<&std::vec::Vec<u8>>}>: std::iter::Iterator`rustcE0599
filter.rs(15, 1): doesn't satisfy `_: std::iter::Iterator`

我相信它的意思是迭代器是在all_unique中使用的,但从我在网上看到的内容来看,似乎没有一种很好的方法可以将我的all_unique函数概括为只使用引用。

我可以用克隆人重写它,但我认为有一种更惯用的方法。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-23 04:55:03

Update:检查this answer for another question为什么filter(all_unique)不能工作。

all_unique不需要使用Vec,也应该实现IntoIterator作为参考。

下面是一个有用的例子,唯一真正的区别是我使用了filter(all_unique),而不是filter(|v| all_unique(v))

代码语言:javascript
复制
use std::hash::Hash;
use std::collections::HashSet;

fn filter_out_duplicates(vec_of_vecs: Vec<Vec<u8>>) -> Vec<Vec<u8>> {
  vec_of_vecs
     .into_iter()
     .filter(|v| all_unique(v))
     .collect()
}

pub fn all_unique<T>(iterable: T) -> bool
where
   T: IntoIterator,
   T::Item: Eq + Hash,
{
   let mut unique = HashSet::new();
   iterable.into_iter().all(|x| unique.insert(x))
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73823038

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档