Rust 1.99 (2024 edition) reference · Vec and HashMap
Rust HashMap get, insert, remove and iteration Method
Look up, add and remove map entries, and iterate in a deterministic order by sorting keys or using BTreeMap.
Rust 1.99 (2024 edition)
Syntax
fn get(&self, k: &Q) -> Option<&V> fn insert(&mut self, k: K, v: V) -> Option<V> fn remove(&mut self, k: &Q) -> Option<V>
Parameters
| Parameter | Description |
|---|---|
get / get_mut |
Option of a reference. |
insert |
Returns the old value, if any. |
contains_key / remove |
Check / delete. |
keys / values / iter |
Iteration in arbitrary order. |
Examples
use std::collections::HashMap;
fn main() {
let mut prices = HashMap::new();
prices.insert("mug", 8.5);
let old = prices.insert("mug", 9.0);
println!("{old:?} {:?} {:?}", prices.get("mug"), prices.get("lamp"));
prices.remove("mug");
println!("{}", prices.contains_key("mug"));
}
Output
Some(8.5) Some(9.0) None false
Run this on your computer — see “Get Started” for setup.
use std::collections::HashMap;
fn main() {
let stock = HashMap::from([("tea", 3), ("mug", 9), ("kettle", 1)]);
let mut names: Vec<_> = stock.keys().collect();
names.sort();
for n in names { println!("{n}: {}", stock[n]); }
}
Output
kettle: 1 mug: 9 tea: 3
Run this on your computer — see “Get Started” for setup.
Related
HashMap::entry· Insert or update a map value in one lookup: count occurrences, append to lists, or insert a default if missing.- Rust Collections: Vec, HashMap and More · tutorial