Maps
A map links keys to values. Its type is map[K, V], and a literal lists
key: value pairs in braces:
map[str, int] ages = {"ana": 31, "luis": 25}
ages["sofia"] = 40 // adds a key
ages["luis"] += 1 // changes a value
print(ages["luis"], len(ages), "ana" in ages) // 26 3 trueKeys can be integers, bool, char, str, or plain enums, which are
compared by their contents, or values of a type with hash and equals
methods, such as one that derives Hash and Equal.
Values can be any type. A map keeps its keys in the order
they were first added, so printing or looping over it is predictable, and
setting an existing key keeps its place.
Reading a key that is missing stops the program with a runtime error, as does
a compound assignment such as += on a missing key, since it reads the old
value; a plain = adds the key. These built-ins work on maps:
| Built-in | Result | Behavior |
|---|---|---|
len(m) |
i64 |
the number of keys |
get(m, key, default) |
value type | the value for key, or default when it is missing |
remove(m, key) |
bool |
removes key and says whether it was there |
keys(m) |
key array | the keys, in order |
values(m) |
value array | the values, in the same order |
map[str, int] counts = {}
for word in split("a b a", " ") do
counts[word] = get(counts, word, 0) + 1
end
print(counts["a"], counts["b"]) // 2 1An empty literal {} needs a declared type, like []. Without one, the key
and value types come from the entries. Maps are references, like arrays:
passing a map to a function shares it, and it may be null. Maps cannot be
printed directly.