home ~ projects ~ socials

Loop Through A BTreeMap In Rust

use std::collections::BTreeMap;

fn main() {
  let mut items: BTreeMap<String, String> = BTreeMap::new();
  items.insert("alfa".to_string(), "bravo".to_string());
  items.insert("charlie".to_string(), "delta".to_string());

  items.iter().for_each(|(key, value)| {
    println!("Key: {} - Value: {}", key, value);
  });
}
Output:
Key: alfa - Value: bravo
Key: charlie - Value: delta

Alternate Approach

use std::collections::BTreeMap;

fn main() {
  let mut items: BTreeMap<String, String> = BTreeMap::new();
  items.insert("alfa".to_string(), "bravo".to_string());
  items.insert("charlie".to_string(), "delta".to_string());

  for (key, value) in items.iter() {
    println!("Key: {} - Value: {}", key, value);
  }
}
Output:
Key: alfa - Value: bravo
Key: charlie - Value: delta
-- end of line --