How to check if a map is empty in Golang?

When the following code:

if map == nil {
    log.Fatal("map is empty")
}

is run, the log statement is not executed, while fmt.Println(map) indicates that the map is empty:

map[]

You can use len:

if len(map) == 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