gpt4 book ai didi

generics - Rust:泛型中的 PartialEq 特征

转载 作者:行者123 更新时间:2023-11-29 07:54:02 25 4
gpt4 key购买 nike

我正在尝试编写一些基本的泛型:

pub struct MyGeneric<T> {
vec: Vec<T>
}

impl<T> MyGeneric<T> {
fn add(&mut self, item: T) {
if !self.vec.contains(&item) {
self.vec.push(item);
}
}
}

但出现错误:

priority_set.rs:23:10: 23:35 error: the trait `core::cmp::PartialEq` is not implemented for the type `T`
priority_set.rs:23 if !self.vec.contains(&item) {
^~~~~~~~~~~~~~~~~~~~~~~~~
error: aborting due to previous error

我曾尝试通过多种方式实现 PartialEq 查看 API 文档,但未能自行找到解决方案。我对 traits 的概念不是很熟悉,所以我需要帮助。

谢谢。

最佳答案

您需要将 T 的所有可能值限制为实现 PartialEq 的值,因为 Vec::contains() 的定义需要它:

pub struct MyGeneric<T> {
vec: Vec<T>
}

// All you need is to add `: PartialEq` to this impl
// to enable using `contains()`
impl<T: PartialEq> MyGeneric<T> {
fn add(&mut self, item: T) {
if !self.vec.contains(&item) {
self.vec.push(item);
}
}
}

fn main()
{
let mut mg: MyGeneric<int> = MyGeneric { vec: Vec::new() };
mg.add(1);
}

大多数情况下,泛型类型需要为其参数指定一些界限,否则将无法验证泛型代码是否正确。例如,这里的 contains() 对项目使用运算符 ==,但并非每种类型都可以定义该运算符。标准特征 PartialEq 定义了运算符 == 所以实现该特征的所有东西都保证有该运算符。

关于generics - Rust:泛型中的 PartialEq 特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26037099/

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