How to check if a map is empty in Golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To check if a map is empty in golang, use the len(myMap) method if it’s equal to 0 it means the map is empty.

Today, I’m going show you how do i check if golang map is empty.

Let’s start

check map is empty or not example

Here, we will create sample map without data and try to check map is empty or not.

package main

func main() {
  mymap := make(map[string]string)
  
  if(len(mymap) == 0){
    println("map is empty")
  } else {
    println("map is not empty")
  }
}

Here, we haven’t added any data in map so output should be map is empty.

Output:

map is empty

Let’s try with data, now we will create sample map with data and try to check is empty or not.

package main

func main() {
  mymap := make(map[string]string)
  mymap["first"] = "aguidehub"
  mymap["second"] = "infinitbility"
  mymap["third"] = "sortoutcode"
  if(len(mymap) == 0){
    println("map is empty")
  } else {
    println("map is not empty")
  }
}

Here, we have added data in map so output should be map is not empty.

Output:

map is not empty

All the best 👍

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Interview Questions

Soon You will get CSS, JavaScript, React Js, and TypeScript So Subscribe to it.

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

Related Posts