Remove duplicates from a custom outline vector

I am trying to remove duplicates in the following example:

struct User {
    reference: String,
    email: String
}

fn main() {

    let mut users: Vec<User> = Vec::new();
    users.push(User { reference: "abc".into(), email: "test@test.com".into() });
    users.push(User { reference: "def".into(), email: "test@test.com".into() });
    users.push(User { reference: "ghi".into(), email: "test1@test.com".into() });

    users.sort_by(|a, b| a.email.cmp(&b.email));
    users.dedup();

}

      

I am getting the (expected) error

src/main.rs:14:8: 14:15 error: no method named `dedup` found for type `collections::vec::Vec<User>` in the current scope
src/main.rs:14  users.dedup();
                      ^~~~~~~
error: aborting due to previous error

      

How to remove duplicates from users

on email

values? Can I implement a function dedup()

for struct User

or do I need to do something else?

+3


source to share


1 answer


If you look at the documentation for Vec::dedup

, you will notice that it is in a small section marked with the following:

impl<T: PartialEq> Vec<T>

      

This means that the methods below only exist when the given constraints are met. In this case, it dedup

does not exist because it User

does not implement the trait PartialEq

. In this particular case, you can simply get it:



#[derive(PartialEq)]
struct User { ... }

      

It is generally a good idea to list all applicable traits; it would probably be nice to get Eq

, Clone

and Debug

.

+6


source







All Articles