Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Rust

Idiom #13 Iterate over map keys and values

Access each key k with its value x from an associative array mymap, and print them.

Traversing each key and each associated object of mymap
use std::collections::BTreeMap;
for (k, x) in &mymap {
    println!("Key={key}, Value={val}", key=k, val=x);
}

You can also print collections in a 'nice' way with `println!("{:?}", mymap);` which is the Debug-representation. You can also use "{:#?}" for the pretty version.

This example works the same if you replace BTreeMap with HashMap.
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;

use Ada.Containers;
for C in My_Map.Iterate loop
   Put_Line ("Key = " & Key (C) & ", Value = " & Element (C));
end loop;

New implementation...