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

后端 未结 1 593
耶瑟儿~
耶瑟儿~ 2021-01-06 09:59

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

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

fn main() {
    let mut users: Vec

        
相关标签:
1条回答
  • 2021-01-06 10:25

    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

    0 讨论(0)
提交回复
热议问题