< 返回版块

github.com/shanliu/lsys 发表于 2023-07-07 21:10

#[derive(Debug, PartialEq)]
struct AreaCodeIndex {
    code: String,
    childs: Vec<AreaCodeIndex>,
}
fn main() {
    let code_str = vec![vec!["aa", "bb"], vec!["aa", "cc"]];
    let mut code_area_data: Vec<AreaCodeIndex> = vec![];
    for tmp in code_str {
        let mut pe_ref = &mut code_area_data; //默认指向 code_area_data
        for tt in tmp {
            pe_ref = if let Some(i) = pe_ref.iter().position(|tc| tc.code == *tt) {
                &mut pe_ref[i].childs
            } else {
                pe_ref.push(AreaCodeIndex {
                    code: tt.to_owned(),
                    childs: vec![],
                });
                &mut pe_ref.last_mut().unwrap().childs
            };
        }
    }
    println!("{:?}", code_area_data);
}


评论区

写评论
作者 github.com/shanliu/lsys 2023-07-08 00:34

还找到一个,先转为hashmap,利用hashmap 的 or_insert

 .entry(ddd.to_string())
                .or_insert(AreaCodeIndex {
                  。。。
                })
                .childs

在转回vec

👇
Pikachu: https://stackoverflow.com/questions/58249193/how-to-find-or-insert-into-a-vec

作者 github.com/shanliu/lsys 2023-07-07 23:40

完美,就是有个unwrap,看着不爽,虽然可以肯定不会panic。

--
👇
Pikachu: https://stackoverflow.com/questions/58249193/how-to-find-or-insert-into-a-vec

Pikachu 2023-07-07 23:15

https://stackoverflow.com/questions/58249193/how-to-find-or-insert-into-a-vec

1 共 3 条评论, 1 页