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)

Create a free account to save this page, take notes and track your progress. Sign in

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

ParameterDescription
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

Example 1
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.

Iterating in sorted order
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.

Was this page helpful?