假设我有一个向量向量vec_of_vecs = vec![vec![1,2],vec![1,3],vec![2,2],vec![2,3]]。过滤掉vec![2,2]的惯用方法是什么?
我的尝试是:
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))
}但是这给了我一个错误信息,我很难解码这个错误
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函数概括为只使用引用。
我可以用克隆人重写它,但我认为有一种更惯用的方法。
发布于 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))
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))
}https://stackoverflow.com/questions/73823038
复制相似问题