gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:04:01 25 4
gpt4 key购买 nike

假设我有以下示例:

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

通过检查 Client 中的 emailphone 来计算此向量中部分重复项的最佳(Rust 惯用)方法是什么?例如 - 在上面的示例中会找到一个重复项。

最佳答案

一种选择是为每个客户创建一个包含(email, phone)HashSet。由于 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);
}

关于rust - 使用自定义函数计算结构 Vec 中的部分重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37698784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com