How to check if a map is empty in Golang?

GoHashmap

Go Problem Overview


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

Go Solutions


Solution 1 - Go

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)

Solution 2 - Go

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Question030View Question on Stackoverflow
Solution 1 - GojacobView Answer on Stackoverflow
Solution 2 - GoMradulView Answer on Stackoverflow