使用自定义函数计算结构 Vec 中的部分重复项

Cab*_*ero 3 rust

假设我有以下示例:

struct Client {
    email: String,
    phone: String,
    details: String
}

fn main() {
    let mut clients: Vec<Client> = Vec::new();

    clients.push(Client {
        email: "john@gmail.com".to_string(),
        phone: "0123456789".to_string(),
        details: "custom details".to_string(),
    });

    clients.push(Client {
        email: "john@gmail.com".to_string(),
        phone: "0123456789".to_string(),
        details: "other details".to_string(),
    });

    clients.push(Client {
        email: "james@gmail.com".to_string(),
        phone: "9876543210".to_string(),
        details: "test".to_string(),
    });  
}
Run Code Online (Sandbox Code Playgroud)

通过检查emailphoneClient? 例如 - 在上面的例子中会发现一个重复。

mal*_*rbo 5

一种选择是创建一个HashSet(email, phone)每一个客户端。由于HashSet只保留唯一元素,我们可以得到重复元素的数量与集合中元素数量的差异clients

use std::collections::HashMap;

struct Client {
    email: String,
    phone: String,
    details: String,
}

fn main() {
    let mut clients: Vec<Client> = Vec::new();

    clients.push(Client {
        email: "john@gmail.com".to_string(),
        phone: "0123456789".to_string(),
        details: "custom details".to_string(),
    });

    clients.push(Client {
        email: "john@gmail.com".to_string(),
        phone: "0123456789".to_string(),
        details: "other details".to_string(),
    });

    clients.push(Client {
        email: "james@gmail.com".to_string(),
        phone: "9876543210".to_string(),
        details: "test".to_string(),
    });

    // use as_str to get a `&str` from a String to avoid copying the string
    let uniques: HashMap<_, _> = clients.iter()
        .map(|c| (c.email.as_str(), c.phone.as_str()))
        .collect();

    let num_dups = clients.len() - uniques.len();

    assert_eq!(1, num_dups);
}
Run Code Online (Sandbox Code Playgroud)