简体   繁体   English

Rust:泛型中的PartialEq特征

[英]Rust: PartialEq trait in generics

I'm trying to write some basic generic: 我正在尝试写一些基本的通用:

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);
        }
    }
}

but getting an error: 但得到一个错误:

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

I have tried to implement PartialEq in several ways looking into API docs, but failed to find a solution by myself. 我试图以几种方式实现PartialEq查看API文档,但我自己找不到解决方案。 I'm not very familiar with traits conception, so I need a help with it. 我对特质概念不太熟悉,所以我需要帮助。

Thanks. 谢谢。

You need to limit all possible values for T to ones that implement PartialEq , because the definition of Vec::contains() requires it: 您需要将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);
}

Generic types require specifying some bounds on their parameters most of the time, otherwise it would not be possible to verify that the generic code is correct. 通用类型需要在大多数时间指定其参数的某些边界,否则将无法验证通用代码是否正确。 Here, for example, contains() is using operator == on items, but not every type may have that operator defined. 例如, contains()在项目上使用operator == ,但并非每个类型都可以定义该运算符。 The standard trait PartialEq defines operator == so everything that implements that trait is guaranteed to have that operator. 标准特征PartialEq定义了operator ==所以实现该特征的所有内容都保证具有该操作符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM