[Solved] How to implement PartialEq for my own structs?


#1

I have the following definition:

pub struct List<T> {
    memory:  Vec<T>,
}

impl<T> List<T> {
    pub fn new() -> Self {
        List {
            memory: Vec::new(),
        }
    }
    // push() add to end of list
    pub fn push(&mut self, value: T) {
        self.memory.push(value);
    }
}

I would get the equivalent of #[derive(PartialEq)] for this type like describe in How can I implement PartialEq?

for example :

let mut listex: List<u32> = List::new();
listex.push(17);
listex.push(18);
listex.push(19);
listex.push(20);            
assert_eq!(listex, [17, 18, 19, 20]);
//  or
println!("{}", listex == [17, 18, 19, 20]);

#2

Go ahead and use #[derive(PartialEq)] to compare lists against other lists.

One way to do other types is to just forward everything that Vec knows how to compare:

impl<T, U> PartialEq<U> for List<T>
    where Vec<T>: PartialEq<U>
{
    fn eq(&self, other: &U) -> bool {
        self.memory.eq(other)
    }
}

But this exposes the fact that you’re using Vec internally, and I don’t think you can generically implement the reverse (Something == List). So you might implement just slices instead:

impl<'a, T: PartialEq> PartialEq<&'a [T]> for List<T>
{
    fn eq(&self, other: &&[T]) -> bool {
        self.memory.eq(other)
    }
}

But this still doesn’t work in reverse.


#3

cuviper, Thank you for your help.

With impl<T, U> PartialEq<U> for List<T>, It’s OK for println!("{}", listex == [17, 18, 19, 20]);

I’m newbie with Rust,

impl<'a, T: PartialEq> PartialEq<&'a [T]> for List<T> is for the reverse => [17, 18, 19, 20] == listex, but I do this listex == [17, 18, 19, 20] doesn’t work. It’s not possible to have two impl PartialEq for List. Is it correct?

I don’t understand very well impl<T, U> PartialEq<U> for List<T> where Vec<T>: PartialEq<U>, Can you explain or give some references explaining it?