How to clear a map in Go?

go

Solution

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)
}

Problem

I'm looking for something like the c++ function `.clear()` for the primitive type `map`. Or should I just create a new map instead? Update: Thank you for your answers. By looking at the answers I just realized that sometimes creating a new map may lead to some inconsistency that we don't want. Consider the following example: ``` var a map[string]string var b map[string]string func main() { a = make(map[string]string) b=a a["hello"]="world" a = nil fmt.Println(b["hello"]) } ``` I mean, this is still different from the `.clear()` function in c++, which will clear the content in the object.

Original source