rsRustPrimer
< Back to module

Collections

HashMap

HashMap<K, V> maps keys to values, like a Java HashMap. It has to be imported from std::collections. insert adds or replaces, get returns an Option<&V> since the key may be missing.

rust
use std::collections::HashMap;
fn main() {
let mut fx: HashMap<String, f64> = HashMap::new();
fx.insert(String::from("EURUSD"), 1.0842);
fx.insert(String::from("EURGBP"), 0.8571);
match fx.get("EURUSD") {
Some(rate) => println!("EURUSD = {rate}"),
None => println!("taux inconnu"),
}
for (pair, rate) in &fx {
println!("{pair} -> {rate}");
}
}
A HashMap's iteration order is not guaranteed and changes between runs. If order matters, use BTreeMap, sorted by key.

The entry API is the most idiomatic tool: it gives access to a key's slot whether it exists or not. or_insert(v) inserts v if the key is missing, then returns a mutable reference to the value. Perfect for counting or accumulating.

rust
use std::collections::BTreeMap;
fn main() {
let trades = [("ACME", 1_000.0), ("Globex", 250.0), ("ACME", -300.0)];
let mut net_by_counterparty: BTreeMap<&str, f64> = BTreeMap::new();
for (counterparty, mtm) in trades {
*net_by_counterparty.entry(counterparty).or_insert(0.0) += mtm;
}
println!("{net_by_counterparty:?}"); // {"ACME": 700.0, "Globex": 250.0}
}

Your turn

Count the number of trades per counterparty with the entry API, then print the result sorted by name.

src/main.rs
use std::collections::BTreeMap;
fn main() {
let counterparties = ["ACME", "Globex", "ACME", "Initech", "ACME", "Globex"];
// compte ici
// attendu : {"ACME": 3, "Globex": 2, "Initech": 1}
}