#[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);
}
1
共 3 条评论, 1 页
评论区
写评论还找到一个,先转为hashmap,利用hashmap 的 or_insert
在转回vec
👇
Pikachu: https://stackoverflow.com/questions/58249193/how-to-find-or-insert-into-a-vec
完美,就是有个unwrap,看着不爽,虽然可以肯定不会panic。
--
👇
Pikachu: https://stackoverflow.com/questions/58249193/how-to-find-or-insert-into-a-vec
https://stackoverflow.com/questions/58249193/how-to-find-or-insert-into-a-vec