How to clear a map in Go?

前端 未结 4 1079
长情又很酷
长情又很酷 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: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).

提交回复
热议问题