snippetgoCritical
How to check if a map is empty in Golang?
Viewed 0 times
emptyhowcheckgolangmap
Problem
When the following code:
is run, the log statement is not executed, while
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
From https://golang.org/ref/spec#Length_and_capacity
len(s) map[K]T map length (number of defined keys)
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.