To check if a map is empty in Go, you can check the length of the map using the len function. If the length is zero, the map is empty.
We can check if a map is empty in Go by using the len function, which returns the number of elements in the map. If the length is zero, the map is empty.
For example,
myMap
. In this example, the map has string keys and integer values.len
function to check if the map is empty. The len
function returns the number of elements in the map.package main
import "fmt"
func main() {
// Declare and initialize an empty map
myMap := map[string]int{}
// Check if the map is empty using len function
if len(myMap) == 0 {
fmt.Println("Is the map empty? Yes")
} else {
fmt.Println("Is the map empty? No")
}
}
Is the map empty? Yes
We can check if a non-empty map is empty in Go by using the len function, which returns the number of elements in the map. If the length is greater than zero, the map is not empty.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.len
function to check if the map is empty. The len
function returns the number of elements in the map.package main
import "fmt"
func main() {
// Declare and initialize a map
myMap := map[string]int{
"one": 1,
"two": 2,
"three": 3,
}
// Check if the map is empty using len function
if len(myMap) == 0 {
fmt.Println("Is the map empty? Yes")
} else {
fmt.Println("Is the map empty? No")
}
}
Is the map empty? No
We can check if a map is empty in Go after clearing its elements using the len function, which returns the number of elements in the map. If the length is zero, the map is empty.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.delete
function.len
function to check if the map is empty. The len
function returns the number of elements in the map.package main
import "fmt"
func main() {
// Declare and initialize a map
myMap := map[string]int{
"one": 1,
"two": 2,
"three": 3,
}
// Clear the map
for k := range myMap {
delete(myMap, k)
}
// Check if the map is empty using len function
if len(myMap) == 0 {
fmt.Println("Is the map empty? Yes")
} else {
fmt.Println("Is the map empty? No")
}
}
Is the map empty? Yes
In this tutorial, we learned How to Check if a Map is Empty in Go language with well detailed examples.