Clearing a map with a pointer value in Go

huangapple go评论89阅读模式
英文:

Clearing a map with a pointer value in Go

问题

我有一个map[string]*list.List,每个列表节点也是一个指针。通过简单地将map设置为nil,是否会清除所有的map、列表和这些指针,并准备好再次使用?

type UnrolledGroup struct {
    next int
    s    []uint32
}

var dictionary = struct {
    m    map[string]*list.List
    keys []string
}{m: make(map[string]*list.List)}

l := list.New()
newGroup := UnrolledGroup{next: 1, s: make([]uint32, groupLen)}
newGroup.s[0] = pos
l.PushBack(&newGroup)
dictionary.m[token] = l

现在这样清除整个内容吗

dictionary.m = nil

通过将dictionary.m设置为nil,只会清除map中的引用,而不会直接清除列表和指针。如果没有其他引用指向这些列表和指针,它们将成为垃圾,并在垃圾回收时被清除。但是,请注意,如果还有其他地方引用了这些列表和指针,它们将不会被立即清除。

英文:

I have a map[string]*list.List and each list node is a pointer too. By simply clearing the map to nil, will all the map and list and all those pointers be cleared and garbage collected and ready to use again?

type UnrolledGroup struct {                                                                                                                                          
    next int
    s    []uint32
 }

 var dictionary = struct {
     m    map[string]*list.List
     keys []string                                                                                                                                                    
 }{m: make(map[string]*list.List)}

 l := list.New()
 newGroup := UnrolledGroup{next: 1, s: make([]uint32, groupLen)}
 newGroup.s[0] = pos
 l.PushBack(&newGroup)
 dictionary.m[token] = l

Now does this clear the whole thing?

 dictionary.m = nil

答案1

得分: 3

这取决于情况:如果某个对象不再“可访问”,它就会被垃圾回收。如果你在地图中保留了对存储内容的其他引用,它就不会被回收。如果地图是这些对象的唯一根引用,它们将被回收。(不要过多考虑这种情况。)

英文:

That depends: Everything is GC'ed if it is no longer "reachable". If you keep other references to the stuff you store in the map it won't be collected. If the map is the sole root to these objects they will get collected. (Don't think too much about such stuff.)

答案2

得分: 0

map 是一个引用类型,也就是说它是指向底层结构的指针类型。你可以将指针设置为 nil,但是如果其他人仍然持有指向相同底层结构的指针,那么他们仍然可以访问其中的所有内容。

英文:

map is a reference type, i.e. it is a pointer type to an underlying structure. You may set your pointer to nil, but if someone else has a pointer to the same underlying structure, then they still have a reference to all the things inside.

huangapple
  • 本文由 发表于 2013年12月18日 20:27:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/20658202.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定