如何从自定义结构体的向量中删除重复项?

6

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

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

我遇到了错误。
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()函数,还是需要做其他事情?

1个回答

12
如果您查看Vec::dedup的文档,您会注意到它在一个小节中,标记为以下内容:
impl<T> Vec<T>
where
    T: PartialEq<T>, 

这意味着它下面的方法仅在满足给定的约束条件时存在。 在这种情况下,dedup不存在,因为User没有实现PartialEq特性。 新的编译器错误甚至明确声明了这一点:

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

在这种情况下,您可以得到PartialEq:
#[derive(PartialEq)]
struct User { /* ... */ }

通常情况下,衍生所有适用的特质都是一个好主意;也许还应该衍生 EqCloneDebug

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

您可以使用 Vec::dedup_by

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

在其他情况下,您可以使用 Vec::dedup_by_key 方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接