【问题标题】:How can I remove duplicates from a vector of custom structs?如何从自定义结构向量中删除重复项?
【发布时间】:2015-06-22 10:34:58
【问题描述】:

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

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() 函数还是必须做其他事情?

【问题讨论】:

    标签: rust


    【解决方案1】:

    如果您查看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

    【讨论】:

      猜你喜欢
      • 2020-01-13
      • 1970-01-01
      • 2014-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多