Skip to content

Collections

The stdlib provides hash-based collection types:

  • HashMap:<K, V>
  • HashSet:<T>
  • HashMapIter:<K, V>
  • HashSetIter:<T>

HashMap:<K, V> stores key-value pairs.

let mut map := HashMap:<str, int>.new();
map["a"] := 10;
map["b"] := 20;
print(map["a"]);
print("a" in map);
print(map.len());

Important HashMap methods include:

  • .set(...)
  • .get(...)
  • .remove(...)
  • .contains(...)
  • .len()
  • .is_empty()
  • .keys()
  • .values()
  • .entries()
  • .clear()
  • .set_all(...)
  • .get_or(...)
  • .iter()
  • .into_iter()

HashSet:<T> stores unique values.

let mut set := HashSet:<int>.new(50, 60, 30);
set.add(10);
set.add(20);
print(10 in set);
print(set.contains(20));
print(set.len());

Important HashSet methods include:

  • .add(...)
  • .remove(...)
  • .contains(...)
  • .len()
  • .is_empty()
  • .values()
  • .clear()
  • .iter()
  • .into_iter()

The iterator types HashMapIter and HashSetIter implement the iterator trait, so you can call .next() manually or use the usual iterator helpers.

let mut it := map.into_iter();
print(it.next());

Use HashMap when values are looked up by key, and HashSet when you only care whether a value is present.