Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...