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}"); }}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}}*counts.entry(name).or_insert(0) += 1;: the star modifies the value behind the mutable reference.
solution
use std::collections::BTreeMap; fn main() { let counterparties = ["ACME", "Globex", "ACME", "Initech", "ACME", "Globex"]; let mut counts: BTreeMap<&str, u32> = BTreeMap::new(); for name in counterparties { *counts.entry(name).or_insert(0) += 1; } println!("{counts:?}");}A single map lookup per element, instead of two with a get followed by an insert. And BTreeMap directly gives alphabetical order.