Maps
Reading a missing key is safe. Writing to a nil map is not. The walk order does not belong to you.
A map is a reference type: the header is copied, the data is shared. The zero map equals nil. Reading from it returns the zero value of the type and does not panic. Writing to a nil map panics. So a map is created with the literal map[string]int{} or with make, if you are going to write to it.
The check "the key was present" looks like this:
n, ok := counts[word]
if !ok {
// ключа не было
}
One variable is not enough: zero can be a real value and also the sign of absence. For sets people often store map[string]struct{}: the empty struct takes no space for the value.
The order of range over a map is random and can change between runs. This is deliberate, so that nobody relies on the order. If you need stable output, take the keys into a slice and sort them.
A map is not safe for simultaneous writes and reads from different goroutines. The race here is not "sometimes a strange result". It is a crash at runtime with concurrent map writes, or silent corruption if you are less lucky. Either the map lives in one goroutine, or a mutex covers it, or you take a specialized structure.
Deletion is delete(m, key). Deleting a missing key is allowed. It is an empty operation. You cannot compare maps with the operator ==, except comparison with nil. The contents are compared by maps.Equal.
Practice
Reading a nil map
What does a read of
var m map[string]intdo for the key"no"?- A panic
- It returns 0 and ok == false
- It returns 0 and ok == true
- The code does not compile
The most common word
Write
MostCommon(words []string) string. Return the word that occurred most often. If several did, return the least one in Go's ordinary string order (abeforeb). For an empty input return an empty string.The order of range
In a test, can you require that
rangeovermap[string]intalways walks the keys in alphabetical order?- Yes, maps in Go are always sorted
- No, the order is not specified
- Yes, if the keys are strings
- Yes, starting with Go 1.22