How to check if a map is empty in Go

Created
Modified

Using len Function

You can use the len function to check if a map is empty. it returns the length of v, according to its type.

len(s) map[K]T: map length (number of defined keys)

package main

import "fmt"

func main() {

  m := map[string]int{}

  // Do
  if len(m) == 0 {
    // map is empty
    fmt.Println("Empty!")
  }

  // Don’t
  if m == nil {
    // m != nil
    fmt.Println("nil Empty!")
  }
}
Empty!

Using nil Identifier

nil is a predeclared identifier in Go. you can use nil to check if the map[string]int has been initialised.

package main

import "fmt"

func main() {

  // not assigned any value
  var m map[string]int

  // Do
  if len(m) == 0 {
    fmt.Println("Empty!")
  }

  // Don’t
  if m == nil {
    fmt.Println("nil Empty!")
  }

  m = map[string]int{}

  // Don’t
  if m == nil {
    // m != nil
    fmt.Println("nil Empty!")
  }
}
Empty!
nil Empty!

You can't use that to check if the map is empty.

Related Tags

#check# #map# #empty#