home ~ socials ~ projects ~ rss

Iterate Over A BTreeMap In Rust Modifying The Items

December 2024
use std::collections::BTreeMap;

fn main() {
  let mut items: BTreeMap<String, String> = BTreeMap::new();
  items.insert("alfa".to_string(), "one".to_string());
  items.insert("bravo".to_string(), "two".to_string());
  items.iter_mut().for_each(|k| {
    if k.0 == "bravo" {
      *k.1 = "CHANGED".to_string();
    }
  });
  dbg!(items);
}
Output:
[_active_nvim_run:13:3] items = {
    "alfa": "one",
    "bravo": "CHANGED",
}
end of line
Share link:
https://www.alanwsmith.com/en/2p/fk/4s/o9/?iterate-over-a-btreemap-in-rust-modifying-the-items