Welcome to OGeek Q&A 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: "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'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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...