Last updated on Sep 19, 2022 by Suraj Sharma
In this tutorial, you will learn how you can check if a map is empty in Golang
I will discuss two ways to check if a map is empty.
We can use the len()
function to check the length of the map, if the length is 0
then the map is empty otherwise, it is not.
package main
import "fmt"
func main () {
demoMap := make(map[string]string)
if len(demoMap) == 0 {
fmt.Println("map is empty")
}
}
Another way is to get a slice of a map's keys and check if its length is 0
or not. If the slice of keys is empty then the map is empty
package main
import "fmt"
func main () {
keys := make([]interface{}, 0)
demoMap := make(map[string]string)
//get a slice of keys from the demoMap
for k, _:= range demoMap {
keys = append(keys, k)
}
if len(keys) == 0 {
fmt.Println("the map is empty")
}
}
Related Solutions
Rate this post
Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.