当键是向量时,我想按键对向量进行分组。
struct Document {
categories: Vec<String>,
body: String
}
let docs = vec![Document {categories: ["rust".to_string(), body: "doc1".to_string()]},
Document {categories: ["clojure".to_string()], body: "doc2".to_string()},
Document {categories: ["java".to_string()], body: "doc3".to_string()},
Document {categories: ["rust".to_string(), "clojure".to_string], body: "doc4".to_string()}];
我想像下面的(category_key, documents)
"rust" => [doc1, doc4]
"clojure" => [doc2, doc4]
"java" => [doc3]
答案 0 :(得分:2)
我是Rust的新手,这对我来说是一个挑战
use std::collections::HashMap;
let result = docs.iter().fold(
HashMap::new(),
|mut init: HashMap<String, Vec<String>>, ref item| {
for category in &item.categories {
let item_body = item.body.clone();
let new_vector: Vec<String> = init
.remove(category)
.map(|mut val| {
val.push(item_body.clone());
val
})
.unwrap_or(vec![item_body.clone()])
.to_vec();
init.insert(category.clone(), new_vector);
}
init
},
);
我确定这段代码可以简化。