HashMap Update In Place And Prune
Mutate every value through values_mut, drop entries with retain, and take ownership of removed values with remove, all without rebuilding the map.
Code
use std::collections::HashMap;
fn main() {
let mut prices: HashMap<&str, u32> = HashMap::new();
prices.insert("cpu", 24_900);
prices.insert("gpu", 62_000);
prices.insert("case", 8_500);
// values_mut:可变借用每个值,就地统一加价,键与结构不变
for cents in prices.values_mut() {
*cents = cents.saturating_add(500);
}
// retain:条件淘汰,只保留满足谓词的条目
prices.retain(|_, cents| *cents >= 10_000);
// remove:值的所有权移出 map
let gpu = prices.remove("gpu");
println!("gpu removed: {gpu:?}");
// HashMap 遍历无序:排序键后输出才稳定
let mut names: Vec<&str> = prices.keys().copied().collect();
names.sort();
for name in names {
println!("{name} -> {}", prices[name]);
}
}How it works
HashMap Update In Place And Prune is built around the function main.
Iteration happens inside for cents in prices.values_mut() — everything outside it runs once.
Putting it to use
The demo output is labeled (gpu removed:), so every printed line maps back to its originating operation.
Core lines
let mut names: Vec<&str> = prices.keys().copied().collect();
names.sort();
Interactive Tools for This Topic
FAQ
- What does HashMap Update In Place And Prune print when run?
- No setup needed: run the file and look for labeled lines like `gpu removed:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.