简体   繁体   English

如何清除Go中的一个map?

[英]How to clear a map in Go?

I'm looking for something like the c++ function .clear() for the primitive type map .我正在为原始类型map寻找类似 c++ function .clear()的东西。

Or should I just create a new map instead?或者我应该创建一个新的 map 吗?

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.通过查看答案,我才意识到有时创建一个新的 map 可能会导致一些我们不想要的不一致。 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.我的意思是,这还是和c++中的.clear() function不同的,后者会清除object中的内容。

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)
}

Unlike C++, Go is a garbage collected language.与 C++ 不同,Go 是一种垃圾收集语言。 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() .你用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).原始数组不会被垃圾收集(直到 b 被垃圾收集或 b 指代其他东西)。

// 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{}

For the method of clearing a map in Go Go中清除一个map的方法

for k := range m {
    delete(m, k)
}

It only works if m contains no key values containing NaN .它仅在m不包含包含NaN的键值时才有效

delete(m, k) doesn't work for any irreflexive key (such as math.NaN() ), but also structs or other comparable types with any NaN float in it. delete(m, k)不适用于任何非自反键(例如math.NaN() ),但也不适用于其中包含任何NaN浮点数的结构或其他类似类型。 Given struct{ val float64 } with NaN val is also irreflexive (Quote by blackgreen comment)给定struct{ val float64 }NaN val 也是非自反的(引自blackgreen评论)


To resolve this issue and support clearing a map in Go, one buildin clear(x) function could be available in the new release, for more details, please refer to add clear(x) builtin, to clear map, zero content of slice, ptr-to-array为解决此问题并支持在Go中清除map,新版本中可以使用一个buildin clear(x) function,更多详细信息,请参阅添加clear(x) builtin,以清除map,slice的零内容,指针到数组

The Go issue for the generic maps package ( https://github.com/golang/go/issues/47649 ) provides maps.Clear .通用maps包 ( https://github.com/golang/go/issues/47649 ) 的 Go 问题提供maps.Clear

The package is found in golang.org/x/exp/maps (experimental, not covered by the compatibility guarantee)该包在golang.org/x/exp/maps中找到(实验性,不在兼容性保证范围内)

// Clear removes all entries from m, leaving it empty.
func Clear[M ~map[K]V, K comparable, V any](m M)

Its usage它的用法

func main() {
    testMap := map[string]int{"gopher": 1, "badger": 2}
    maps.Clear(testMap)
    fmt.Println(testMap)
    
    testMap["zebra"] = 2000
    fmt.Println(testMap)
}

Run the code here https://go.dev/play/p/qIdnGrd0CYs?v=gotip在此处运行代码https://go.dev/play/p/qIdnGrd0CYs?v=gotip

The value of an uninitialized map is nil . 未初始化的地图的值为零

map = nil; 

Should do. 应该做。 Then of course, you need to create a new map. 当然,您需要创建一个新地图。

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
-----------

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM