HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoCritical

How to check if a map is empty in Golang?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
emptyhowcheckgolangmap

Problem

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[]

Solution

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)

Code Snippets

if len(m) == 0 {
    ....
}

Context

Stack Overflow Q#35005261, score: 228

Revisions (0)

No revisions yet.