bbrodriges
bbrodriges

Reputation: 713

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.

Upvotes: 5

Views: 3018

Answers (1)

hamstergene
hamstergene

Reputation: 24439

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.

Upvotes: 6

Related Questions