如何从Rust中借用的泛型数组创建哈希集?

如何从Rust中借用的泛型数组创建哈希集?,rust,Rust,我有一个函数,它使用两个借用的泛型数组T,我想从这些数组中创建HashSets,以便比较它们 我想我可以做这样的事情: pub fn sublist<T: PartialEq>(first_list: &[T], second_list: &[T]) -> bool { let first_set: HashSet<T> = first_list.iter().collect(); let second_set: HashSet<T&g

我有一个函数,它使用两个借用的泛型数组
T
,我想从这些数组中创建
HashSet
s,以便比较它们

我想我可以做这样的事情:

pub fn sublist<T: PartialEq>(first_list: &[T], second_list: &[T]) -> bool {
  let first_set: HashSet<T> = first_list.iter().collect();
  let second_set: HashSet<T> = second_list.iter().collect();

  first_set.is_subset(&second_set)
}
但我看到了这些错误:

the trait bound `T: std::cmp::Eq` is not satisfied

the trait `std::cmp::Eq` is not implemented for `T`

note: required because of the requirements on the impl of `std::cmp::Eq` for `&T`
note: required because of the requirements on the impl of `std::iter::FromIterator<&T>` for `std::collections::HashSet<&T>`
特性绑定'T:std::cmp::Eq'不满足
没有为'T'实现特性'std::cmp::Eq'`
注:之所以需要,是因为“&T”的“std::cmp::Eq”impl中的要求`
注意:由于对`std::collections::HashSet`的`std::iter::FromIterator` impl的要求,因此需要此选项`
我不明白如何从对数组的引用创建新的数据结构。问题在于这些数组是借用的,还是归根结底是
PartialEq
上的trait绑定


如果出于任何原因,我无法修改函数签名,我如何使用哈希集来比较集合呢?

要使用
HashSet
您的函数需要有
Eq
Hash
特征边界:

use std::hash::Hash;
use std::collections::HashSet;

pub fn sublist<T: Eq + Hash>(first_list: &[T], second_list: &[T]) -> bool {
  let first_set: HashSet<&T> = first_list.iter().collect();
  let second_set: HashSet<&T> = second_list.iter().collect();

  first_set.is_subset(&second_set)
}

其他选项包括
T:Ord
和使用
BTreeSet

HashSet
需要
Eq
PartialEq
是不够的。如果您还没有找到特性绑定的
散列
,那么您也可能会遇到一个错误。这意味着无法使用
散列集
来比较这些数组?手动进行比较是惯用的方法,还是我应该使用其他集合?Rust需要预先声明泛型的任何功能。如果您只需要使用
PartialEq
,那么就不能使用任何类型的散列或有序容器来提高检查效率。您可以将它们放入
Vec
中,但如果您甚至不能对它们进行排序(需要
Ord
),那么为什么还要麻烦呢?在循环中直接使用是我在给定约束下看到的唯一选项。
the trait bound `T: std::cmp::Eq` is not satisfied

the trait `std::cmp::Eq` is not implemented for `T`

note: required because of the requirements on the impl of `std::cmp::Eq` for `&T`
note: required because of the requirements on the impl of `std::iter::FromIterator<&T>` for `std::collections::HashSet<&T>`
use std::hash::Hash;
use std::collections::HashSet;

pub fn sublist<T: Eq + Hash>(first_list: &[T], second_list: &[T]) -> bool {
  let first_set: HashSet<&T> = first_list.iter().collect();
  let second_set: HashSet<&T> = second_list.iter().collect();

  first_set.is_subset(&second_set)
}