Working a map in Go
The comma-ok read, delete, and the deliberate randomness of iteration.
func mapOps() (int, bool, []string) {
steps := map[string]int{"basics": 39, "traits": 19, "errors": 15}
missing, ok := steps["nope"]
delete(steps, "errors")
steps["cli"] = 12
keys := make([]string, 0, len(steps))
for key := range steps {
keys = append(keys, key)
}
sort.Strings(keys)
return missing + len(steps), ok, keys
}
How it works
- A missing key returns the zero value, so ask with two results.
deleteis a no-op on a key that is not there.- Iteration order is randomised on purpose; sort the keys.
Keywords and builtins used here
appendbooldeleteforfuncintlenmakemaprangereturnstring
The run, in numbers
- Lines
- 15
- Characters to type
- 326
- Tokens
- 102
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 68 seconds.
Step 5 of 9 in Arrays, slices & maps, step 20 of 30 in Language basics.