The standard library
Slide 48 of 85
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 every field is 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) write into a mut map. Replacing a value keeps its key's place; deleting a key and setting it again moves it to the end.
  • 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, which is what makes echoing a map the same on every run.
  • fromTable(t) and toTable(m) cross to and from a Table of two-cell rows, for a map of Str to Str. 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 and not walked: m[0] and for each … in m are compile errors, and walking keys(m) is how. The module is map for short — map.keys(m) — and the builtin map(values, f) is still the builtin: a call on the name is the module, and a bare call 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)
}
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")
}