HashMap Drain Moves Entries
Move every entry out of a HashMap with drain, filter owned pairs into a Vec, and verify the map is empty afterward.
Code
use std::collections::HashMap;
fn main() {
let mut inventory: HashMap<&str, u32> = HashMap::new();
inventory.insert("bolts", 12);
inventory.insert("nuts", 30);
inventory.insert("washers", 8);
inventory.insert("screws", 44);
// drain moves owned pairs out of the map
let low: Vec<(&str, u32)> = inventory
.drain()
.filter(|(_, count)| *count < 20)
.collect();
println!("low stock: {low:?}");
// entries that missed the filter are removed as well
println!("remaining: {}", inventory.len());
inventory.insert("gears", 5);
let keys: Vec<&str> = inventory.drain().map(|(name, _)| name).collect();
println!("drained keys: {keys:?}");
println!("empty: {}", inventory.is_empty());
}How it works
HashMap Drain Moves Entries keeps everything in the function main.
What to watch for
- The import surface (if any) is all standard library, all versioned with the language itself.
Using it
The main signature reads fn main()
The demo output is labeled (low stock:, remaining:, drained keys:), so every printed line maps back to its originating operation.
Key statements
let keys: Vec<&str> = inventory.drain().map(|(name, _)| name).collect();
.filter(|(_, count)| *count < 20)
.collect();
Interactive Tools for This Topic
FAQ
- What does HashMap Drain Moves Entries print when run?
- The script runs standalone; its 4 labeled outputs include `low stock:`, `remaining:`, `drained keys:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.