May 28, 2023

How to clear a map in Go?

You should probably just create a new map. There’s no real reason to bother trying to clear an existing one, unless the same map is being referred to by multiple pieces of code and one piece explicitly needs to clear out the values such that this change is visible to the other pieces of code.

So yeah, you should probably just say

mymap = make(map[keytype]valtype)

If you do really need to clear the existing map for whatever reason, this is simple enough:

for k := range m {
    delete(m, k)
}

Leave a Reply