The maps package in Go
Iterating a map's keys and values without writing the loop.
func mapHelpers() ([]string, int, bool) {
steps := map[string]int{"basics": 39, "traits": 19, "errors": 15}
keys := slices.Collect(maps.Keys(steps))
slices.Sort(keys)
total := 0
for value := range maps.Values(steps) {
total += value
}
copied := maps.Clone(steps)
delete(copied, "errors")
return keys, total, maps.Equal(steps, copied)
}
How it works
maps.Keysreturns an iterator, not a slice.slices.Collectturns that iterator into a slice.maps.Cloneandmaps.Equaldo the obvious things.
Keywords and builtins used here
booldeleteforfuncintmaprangereturnstring
The run, in numbers
- Lines
- 15
- Characters to type
- 338
- Tokens
- 99
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 57 seconds.
Step 2 of 5 in Collections & text, step 10 of 26 in Standard library & project layout.