How to clear a map in Go?

前端 未结 4 921
长情又很酷
长情又很酷 2021-01-30 05:59

I\'m looking for something like the c++ function .clear() for the primitive type map.

Or should I just create a new map instead?

Updat

相关标签:
4条回答
  • 2021-01-30 06:34

    If you are trying to do this in a loop, you can take advantage of the initialization to clear out the map for you. For example:

    for i:=0; i<2; i++ {
        animalNames := make(map[string]string)
        switch i {
            case 0:
                animalNames["cat"] = "Patches"
            case 1:
                animalNames["dog"] = "Spot";
        }
    
        fmt.Println("For map instance", i)
        for key, value := range animalNames {
            fmt.Println(key, value)
        }
        fmt.Println("-----------\n")
    }
    

    When you execute this, it clears out the previous map and starts with an empty map. This is verified by the output:

    $ go run maptests.go 
    For map instance 0
    cat Patches
    -----------
    
    For map instance 1
    dog Spot
    -----------
    
    0 讨论(0)
  • 2021-01-30 06:37

    Unlike C++, Go is a garbage collected language. You need to think things a bit differently.

    When you make a new map

    a := map[string]string{"hello": "world"}
    a = make(map[string]string)
    

    the original map will be garbage-collected eventually; you don't need to clear it manually. But remember that maps (and slices) are reference types; you create them with make(). The underlying map will be garbage-collected only when there are no references to it. Thus, when you do

    a := map[string]string{"hello": "world"}
    b := a
    a = make(map[string]string)
    

    the original array will not be garbage collected (until b is garbage-collected or b refers to something else).

    0 讨论(0)
  • 2021-01-30 06:42
    // Method - I , say book is name of map
    for k := range book {
        delete(book, k)
    }
    
    // Method - II
    book = make(map[string]int)
    
    // Method - III
    book = map[string]int{}
    
    0 讨论(0)
  • 2021-01-30 07:01

    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)
    }
    
    0 讨论(0)
提交回复
热议问题