How to check if a map is empty in Golang?
November 12, 2022Hi 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 👍