When the following code:
m := make(map[string]string)
if m == nil {
log.Fatal("map is empty")
}
is run, the log statement is not executed, while fmt.Println(m)
indicates that the map is empty:
map[]
You can use len
:
if len(m) == 0 {
....
}
From https://golang.org/ref/spec#Length_and_capacity
len(s) map[K]T map length (number of defined keys)
The following example demonstrates both the nil check and the length check that can be used for checking if a map is empty
package main
import (
"fmt"
)
func main() {
a := new(map[int64]string)
if *a == nil {
fmt.Println("empty")
}
fmt.Println(len(*a))
}
Prints
empty
0
new(map[int64]string)
return a uninitialized pointer to a map. You can't use that to check if the map is empty.
a
nor *a
are uninitialized. new()
doesn't initialize the memory it allocates, but it zeros it. See go.dev/doc/effective_go#allocation_new The zero value of a map is equal to nil
. In some aspects, it behaves like an empty map: you can check its size with len()
, loop over it (won't execute loop body), delete an entry (won't do anything), print it (will print map[]
), etc. Trying to add an entry will panic though.
Dec 4, 2022 at 14:19
*a
can be said to be uninitialized, but it's in a well-defined state and usable, e.g. for len(*a)
. That's quite different from languages like C, where "uninitialized" means "completely unusable until you initialize it".
Dec 4, 2022 at 15:14
nil
or can be initialized and with 0 value inside that. This are two different situations!