Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a map is empty in Golang?

Tags:

hashmap

go

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[] 
like image 200
030 Avatar asked Jan 26 '16 00:01

030


People also ask

How do you check whether a map is empty or not in Golang?

Using len() function We can use the len() function to check the length of the map, if the length is 0 then the map is empty otherwise, it is not.

Is Empty map nil Golang?

A nil map is equivalent to an empty map except that elements can't be added. The len function returns the size of a map, which is the number of key-value pairs.

Can a map be nil in go?

A map maps keys to values. The zero value of a map is nil . A nil map has no keys, nor can keys be added.


2 Answers

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)

like image 128
jacob Avatar answered Sep 28 '22 08:09

jacob


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 
like image 20
Mradul Avatar answered Sep 28 '22 06:09

Mradul