Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear a map in Go?

Tags:

go

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.

like image 811
lavin Avatar asked Dec 11 '12 01:12

lavin


People also ask

How do you clear a map in Golang?

Create Empty Map in Golang To create an empty Map in Go language, we can either use make() function with map type specified or use map initializer with no key:value pairs given. Create an empty Map: string->string using make() function with the following syntax.

How do I delete a map key?

To delete a key from a map, we can use Go's built-in delete function. It should be noted that when we delete a key from a map, its value will also be deleted as the key-value pair is like a single entity when it comes to maps in Go.

How do you initialize an empty map in Golang?

Go by Example: Maps To create an empty map, use the builtin make : make(map[key-type]val-type) . Set key/value pairs using typical name[key] = val syntax. Printing a map with e.g. fmt. Println will show all of its key/value pairs.

How do maps work in Go?

In Go language, a map is a powerful, ingenious, and versatile data structure. Golang Maps is a collection of unordered pairs of key-value. It is widely used because it provides fast lookups and values that can retrieve, update or delete with the help of keys. It is a reference to a hash table.


1 Answers

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) } 
like image 65
Lily Ballard Avatar answered Sep 18 '22 06:09

Lily Ballard