本文介绍了如何从自定义结构向量中删除重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试删除以下示例中的重复项:

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();
}

我收到错误

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();
   |           ^^^^^
   |

如何通过 email 值从 users 中删除重复项?我可以为 struct User 实现 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?

推荐答案

如果您查看 Vec::dedup,您会注意到它位于由以下标记的小部分中:

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>, 

这意味着它下面的方法在满足给定的约束时存在.在这种情况下, dedup 不存在,因为 User 没有实现 PartialEq 特性.较新的编译器错误甚至明确指出:

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`

在这种特殊情况下,您可以导出PartialEq:

In this particular case, you can derive PartialEq:

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

推导出所有适用的特征通常是一个好主意;导出EqCloneDebug可能是个好主意.

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.

如何通过 email 值从 users 中删除重复项?

您可以使用 Vec::dedup_by:

You can use Vec::dedup_by:

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

在其他情况下,您可能可以使用 Vec::dedup_by_key

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

这篇关于如何从自定义结构向量中删除重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 01:52