How to clear a map in Go?

前端 未结 4 1013
长情又很酷
长情又很酷 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
    -----------
    

提交回复
热议问题