Rust: PartialEq property in generics

I am trying to write a basic generic file:

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 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 tried to implement PartialEq in several ways by looking at the API docs but couldn't find a solution myself. I'm not very familiar with the concept of traits, so I need help.

Thank.

+3


source to share


1 answer


You need to constrain all possible values ​​for T

those that implement PartialEq

, because the definition Vec::contains()

requires the following:

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 some constraints on their parameters most of the time, otherwise it would be impossible to verify that the generic code is correct. Here, for example, contains()

uses an operator ==

on elements, but not every type can have this operator. A standard trait PartialEq

defines an operator ==

, so anything that implements this trait is guaranteed to have this operator.

+5


source







All Articles