How to check if a map is empty in Golang?

86,302

Solution 1

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

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
Share:
86,302

Related videos on Youtube

030
Author by

030

Updated on March 15, 2022

Comments

  • 030
    030 over 2 years

    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[]
    
    • Cirelli94
      Cirelli94 over 4 years
      This question has a lot of upvote but I think there's a little misunderstanding here: a map can be nil or can be initialized and with 0 value inside that. This are two different situations!
  • Slava Bacherikov
    Slava Bacherikov almost 6 years
    For those who is wondering about complexity it is O(1). Here's implementation.
  • super
    super over 3 years
    new(map[int64]string) return a uninitialized pointer to a map. You can't use that to check if the map is empty.
  • Alessandro Argentieri
    Alessandro Argentieri almost 3 years
    @Mradul you don't need a pointer to a map or a slice: they're already pointers!