如何检查 Golang 的地图是否是空的?

当下列代码:

m := make(map[string]string)
if m == nil {
log.Fatal("map is empty")
}

则不执行 log 语句,而 fmt.Println(m)指示映射为空:

map[]
101290 次浏览

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