Vector 如何检查结构集合的字段中是否有重复的值?

Vector 如何检查结构集合的字段中是否有重复的值?,vector,struct,rust,duplicates,Vector,Struct,Rust,Duplicates,我想从一些结构的向量中提取一些数据,以检查是否存在重复项 #[derive(Debug)] struct Test { id: i32, name: String } fn main() { let test1 = Test { id: 1, name: String::from("one") }; let test2 = Test { id: 2, name: String::from("two") }; let

我想从一些结构的向量中提取一些数据,以检查是否存在重复项

#[derive(Debug)]
struct Test {
    id: i32,
    name: String
}

fn main() {
    let test1 = Test { id: 1, name: String::from("one") };
    let test2 = Test { id: 2, name: String::from("two") };
    let test3 = Test{ id: 3, name: String::from("one") };
    
    let mut small_collection = Vec::new();
    small_collection.push(test1);
    small_collection.push(test2);
    small_collection.push(test3);
    
     let uniques: Vec<String> = small_collection.iter()
        .map(|x| x.name.as_str())
        .collect();

    // let num_dups = clients.len() - uniques.len();
}
该程序创建一个小的结构集合。但是,在创建向量之后,我想检查Test.name字段中是否存在重复项

所以我尝试迭代并创建一个新的向量。如果“我的收藏”和“缩减名称”的len相同,则不存在重复项。在这种情况下,值1显示两次

但是我被卡住了,有什么帮助吗?

您可以通过调用Vec,然后在Vec上按如下方式将Vec简化为唯一值:

你好,回答问题了吗?切片是对向量的一种轻微抽象。
#[derive(Debug)]
struct Test {
    id: i32,
    name: String
}

fn main() {
    let test1 = Test { id: 1, name: String::from("one") };
    let test2 = Test { id: 2, name: String::from("two") };
    let test3 = Test { id: 3, name: String::from("one") };

    let mut small_collection = Vec::new();
    small_collection.push(test1);
    small_collection.push(test2);
    small_collection.push(test3);

    let mut uniques: Vec<&str> = small_collection.iter()
        .map(|x| x.name.as_str())
        .collect();

    uniques.sort();
    uniques.dedup();

    let num_dups = small_collection.len() - uniques.len();
    assert_eq!(num_dups, 1);
}
use std::collections::HashSet;

#[derive(Debug)]
struct Test {
    id: i32,
    name: String
}

fn main() {
    let test1 = Test { id: 1, name: String::from("one") };
    let test2 = Test { id: 2, name: String::from("two") };
    let test3 = Test { id: 3, name: String::from("one") };

    let mut small_collection = Vec::new();
    small_collection.push(test1);
    small_collection.push(test2);
    small_collection.push(test3);

    let uniques_len = small_collection.iter()
        .map(|x| x.name.as_str())
        .collect::<HashSet<&str>>()
        .len();

    let num_dups = small_collection.len() - uniques_len;
    assert_eq!(num_dups, 1);
}