Group Records By Key With Entry
Group sales into a map of vectors with entry or_default: the first occurrence allocates the bucket and later ones borrow it, with sorted keys for stable output.
Code
use std::collections::HashMap;
struct Sale {
region: String,
cents: i32,
}
fn main() {
let sales = vec![
Sale { region: "eu".into(), cents: 120 },
Sale { region: "us".into(), cents: 80 },
Sale { region: "eu".into(), cents: 45 },
];
// entry 需要键的所有权:首次进入 or_default() 分配新 Vec,
// 之后同一键借出已有 Vec 直接 push
let mut by_region: HashMap<String, Vec<i32>> = HashMap::new();
for sale in &sales {
by_region
.entry(sale.region.clone())
.or_default()
.push(sale.cents);
}
// HashMap 遍历顺序随机:键排序后输出可复现
let mut keys: Vec<&String> = by_region.keys().collect();
keys.sort();
for key in keys {
let totals: i32 = by_region[key].iter().sum();
println!("{key}: {:?} = {totals}", by_region[key]);
}
}How the snippet works
Group Records By Key With Entry comes down to the function main.
The file repeats itself only inside for sale in &sales.
Iteration is driven by for sale in &sales and for key in keys.
Statements that matter
let totals: i32 = by_region[key].iter().sum();
let mut keys: Vec<&String> = by_region.keys().collect();
keys.sort();
Interactive Tools for This Topic
FAQ
- How do you run Group Records By Key With Entry?
- Nothing to install first — run the file and the program does the rest.
Report a problem with this exampleOpens a pre-filled issue on GitHub.