To clear all key-value pairs from a map in Go, you can reinitialize the map or delete each key individually using a loop. Both methods effectively empty the map.
We can clear all key-value pairs from a map in Go by reinitializing the map, which removes all elements from the map.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.myMap
.fmt.Println
function to verify that the map is empty.package main
import "fmt"
func main() {
// Declare and initialize a map
myMap := map[string]int{
"one": 1,
"two": 2,
"three": 3,
}
// Clear all key-value pairs by reinitializing the map
myMap = make(map[string]int)
// Print the contents of the map
fmt.Println(myMap)
}
map[]
We can reinitialize an already empty map in Go, and it will still be empty.
For example,
myMap
. In this example, the map has string keys and integer values.myMap
.fmt.Println
function to verify that the map is still empty.package main
import "fmt"
func main() {
// Declare and initialize an empty map
myMap := map[string]int{}
// Clear the map by reinitializing it
myMap = make(map[string]int)
// Print the contents of the map
fmt.Println(myMap)
}
map[]
We can delete each key individually from a map to clear all key-value pairs in Go.
For example,
myMap
and inserting some key-value pairs into it. In this example, the map has string keys and integer values.delete
function.fmt.Println
function to verify that the map is empty.package main
import "fmt"
func main() {
// Declare and initialize a map
myMap := map[string]int{
"one": 1,
"two": 2,
"three": 3,
}
// Clear the map by deleting each key individually
for key := range myMap {
delete(myMap, key)
}
// Print the contents of the map
fmt.Println(myMap)
}
map[]
In this tutorial, we learned How to Clear All Key-Value Pairs from a Map in Go language with well detailed examples.