gpt4 book ai didi

rust - 如何在Rust中从通用类型的借用数组创建HashSet?

转载 作者:行者123 更新时间:2023-12-03 11:44:27 30 4
gpt4 key购买 nike

我有一个函数,接受两个借用的通用类型为T的数组,我想从这些数组创建HashSet,以便可以对其进行比较。
我以为我可以做这样的事情:

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)
}
但是我最终遇到以下错误:
a value of type `std::collections::HashSet<T>` cannot be built from an iterator over elements of type `&T`

value of type `std::collections::HashSet<T>` cannot be built from `std::iter::Iterator<Item=&T>`

help: the trait `std::iter::FromIterator<&T>` is not implemented for `std::collections::HashSet<T>`
由于错误的第一行,我想我可能可以这样解决(我只是将哈希集类型更改为引用 &T):
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>`
我不明白如何从对数组的引用中创建新的数据结构。难道是借用了这些数组是一个问题,还是归根结底是 PartialEq上的特征成为问题?
如果出于某种原因我不能修改函数签名,该如何使用哈希集比较集合呢?

最佳答案

要使用HashSet,您的函数需要具有EqHash特征范围:

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)
}
如果您只知道 TPartialEq,则可以像这样实现它:
pub fn sublist<T: PartialEq>(first_list: &[T], second_list: &[T]) -> bool {
first_list.iter().all(|v| second_list.contains(v))
}
其他选项包括 T: Ord和使用 BTreeSet

关于rust - 如何在Rust中从通用类型的借用数组创建HashSet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64614461/

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