The standard librarySlide 48 of 86
48MapThe standard library

Maps

hive.map.Map<K, T> is the one collection that is not a vector. A key is compared and hashed whole, so it is a Str, Int, Float, Bool, Atom, or a declared type whose fields are all one of those. new() says only "empty", so it takes its type from where it lands — a declaration, a return, or a parameter — or, bound with :=, from the first later use that says it, such as set(m, "a", 1), and keeps it.

  • set(m, key, value) and delete(m, key) are procs that take the map mut. Replacing a value keeps its key's place; deleting a key and setting it again moves it to the end.
  • plus(m, key, value) and minus(m, key) do the same but answer with a new map and leave m as it was, so m needs no mut.
  • get(m, key) answers with a Result whose Error carries false; has(m, key) asks the same without the value.
  • keys(m) and values(m) are fresh vectors in the order the keys were set, so echoing a map prints the same on every run.
  • fromTable(t) and toTable(m) convert between a map of Str to Str and a Table of two-cell rows. fromTable skips a row with fewer than two cells, and a key given twice keeps its first place and its last value.

A map is not indexed or walked: m[0] and for each … in m are compile errors; walk keys(m) instead. The module is map for short — map.keys(m) — and the builtin map(values, f) is still there: map. and a name is the module, a bare map(…) the builtin. A map cannot be encoded or sent to a service; send its pairs as a vector of a type declared for them.

Setting, getting and walking
proc main(): void {
	mut hive.map.Map<Str, Int> counts = hive.map.new()
	hive.map.set(counts, "bees", 12)
	hive.map.set(counts, "hives", 3)

	if hive.map.get(counts, "bees") is Result.Ok(n) {
		echo n
	}
	echo hive.map.has(counts, "wasps")
	hive.map.delete(counts, "hives")
	echo hive.map.keys(counts)
	echo hive.map.values(counts)
	echo hive.map.plus(counts, "wasps", 2)
	echo counts
}
Crossing to and from a Table
proc main(): void {
	mut hive.map.Map<Str, Str> labels = hive.map.new()
	hive.map.set(labels, "bees", "many")
	echo hive.map.toTable(labels)

	echo hive.map.get(hive.map.fromTable([["wasps", "few"]]), "wasps")
}