如何在Go中清除地图? [英] How to clear a map in Go?

查看:112
本文介绍了如何在Go中清除地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为基元类型 map 寻找类似c ++函数 .clear()的东西。



或者我应该创建一个新的地图吗?

更新:感谢您的回答。通过查看答案,我才意识到有时创建新地图可能会导致我们不想要的一些不一致。考虑下面的例子:

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

我的意思是,这仍然不同于c ++中的 .clear()函数,它将清除对象中的内容。 >解决方案

你应该创建一个新的地图。除非相同的地图被多个代码片段引用,并且一个片段明确需要清除这些值,使得这些更改对于其他代码片段可见,否则没有真正的理由去试图清除现有的片段。 / p>

所以是的,你可能应该说

  mymap = make map [keytype] valtype)






无论出于何种原因,都需要清除现有地图,这很简单:

  for k:= range m {
删除(m,k)
}


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.

解决方案

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

这篇关于如何在Go中清除地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆