简体   繁体   中英

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. 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:

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. The standard trait PartialEq defines operator == so everything that implements that trait is guaranteed to have that operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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