Clear a map in Go

0
1
Clear a map in Go
Clear a map in Go

In this post, I will share with you a quick tip to clear a map in Go.

There are two ways to clear a map in Go.

First way is by common sense, you can iterate through the map and delete each individual key one by one.

myMap := make(map[string]string)

...// assign some values and do something with map

// iterate through each key to delete
for key := range myMap {
	delete(myMap, key)
}

Another way to re-init the map by allocating a new map using make().

myMap := make(map[string]string) 

...// assign some values and do something with map 

// clean up
myMap := make(map[string]string)

That’s it!