Menu Close

Go – How to check if a map is empty in go

In this tutorial, We are going to learn about how to check if a map is empty in go. map is a collection of unordered pairs of key-value.

len() built-in function is used to get the length the of map. If len() function returns 0 then map is empty.

Syntax:

length = len(map_name)

or

if len(map_name) == 0 {
    fmt.Println("It's an empty map")
}

Go code to check empty map:

package main

import (

  "fmt"

)

func main() {

  m := map[string]int {}
  
  if len(m) == 0 {
      fmt.Println("It's an empty map")
  } else {
      fmt.Println("Map is not empty")
  }
}

When we do it by len of map like len(map), in this case, It returns number of entries key-value pair present in map.

Example:

map = {"sun": a, "mon": 2, "tue": 3}

length of map = len(map)

length of map = 3

Go code to check length of map

package main

import (

  "fmt"

)

func main() {

  m := map[string]int {

  "sun": 0,
  "mon": 1,
  "tue": 3,

  }

  fmt.Println("Length of map: ", len(m))

}

Output:

Length of map: 3

To learn more about golang, You can refer given below link:

https://www.techieindoor.com/go-lang-tutorial/

References:

https://golang.org/pkg/

Posted in golang, Miscellaneous

Leave a Reply

Your email address will not be published. Required fields are marked *