按字段对结构的向量进行分组

我想创建一个包含结构中所有匹配字段id的向量,处理这个新的向量,然后重复这个过程。基本上将具有匹配字段id的结构分组在一起。

有没有一种不使用不稳定特性drain_filter的方法可以做到这一点?

#![feature(drain_filter)]

#[derive(Debug)]
struct Person {
    id: u32,
}

fn main() {

    let mut people = vec![];

    for p in 0..10 {
        people.push(Person { id: p });
    }

    while !people.is_empty() {
        let first_person_id = people.first().unwrap().id;

        let drained: Vec<Person> = people.drain_filter(|p| p.id == first_person_id).collect();

        println!("{:#?}", drained);
    }

}

Playground

转载请注明出处:http://www.txqp3.com/article/20230526/2486166.html