snippetgoCritical
How to clear a map in Go?
Viewed 0 times
howclearmap
Problem
I'm looking for something like the c++ function
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:
I mean, this is still different from the
.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.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
If you do really need to clear the existing map for whatever reason, this is simple enough:
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)
}Code Snippets
mymap = make(map[keytype]valtype)for k := range m {
delete(m, k)
}Context
Stack Overflow Q#13812121, score: 168
Revisions (0)
No revisions yet.