Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove duplicates from a vector of custom structs?

Tags:

rust

I'm trying to remove duplicates in the below example:

struct User {
    reference: String,
    email: String,
}

fn main() {
    let mut users: Vec<User> = Vec::new();
    users.push(User {
        reference: "abc".into(),
        email: "[email protected]".into(),
    });
    users.push(User {
        reference: "def".into(),
        email: "[email protected]".into(),
    });
    users.push(User {
        reference: "ghi".into(),
        email: "[email protected]".into(),
    });

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

I'm getting the error

error[E0599]: no method named `dedup` found for type `std::vec::Vec<User>` in the current scope
  --> src/main.rs:23:11
   |
23 |     users.dedup();
   |           ^^^^^
   |

How can I remove duplicates from users by email values? Can I implement the dedup() function for struct User or do I have to do something else?

like image 622
Caballero Avatar asked Dec 25 '22 17:12

Caballero


1 Answers

If you look at the documentation for Vec::dedup, you'll note that it's in a little section marked by the following:

impl<T> Vec<T>
where
    T: PartialEq<T>, 

This means that the methods below it exist only when the given constraints are satisfied. In this case, dedup isn't there because User doesn't implement the PartialEq trait. Newer compiler errors even state this explicitly:

   = note: the method `dedup` exists but the following trait bounds were not satisfied:
           `User : std::cmp::PartialEq`

In this particular case, you can derive PartialEq:

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

It's generally a good idea to derive all applicable traits; it would probably be a good idea to also derive Eq, Clone and Debug.

How can I remove duplicates from users by email values?

You can use Vec::dedup_by:

users.dedup_by(|a, b| a.email == b.email);

In other cases, you might be able to use Vec::dedup_by_key

like image 142
DK. Avatar answered Dec 31 '22 00:12

DK.