如何在Go中删除struct对象? [英] How to delete struct object in go?

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

问题描述

假设我具有以下结构:

type Person struct {
    name string
    age  int
}

如果我使用该结构作为对象

If I make an object of that struct

person1 := Person{name: "Name", age: 69}

如果我将此对象设置为nil

If I set this object to nil

person1 = nil

它不起作用,实际上是类型分配错误,但它适用于地图和切片.那么,我将如何删除该对象(即取消分配)呢?我查看了内置的delete文档,但它从给定的映射中删除了一个条目.谢谢.

it doesn't work, in fact it's a type assignment error, but it works for maps and slices. So, how otherwise would I remove the object i.e deallocate? I looked at the documentation for delete builtin but it removes an entry from a given map. Thanks.

推荐答案

Go是一种垃圾收集语言.您不应该这样做,也不能从内存中删除对象.这样做是垃圾收集者的职责责任,并且它是自动执行的.当对象变得无法访问时,垃圾收集器会正确地从内存中删除它们.

Go is a garbage collected language. You are not supposed to, and you cannot delete objects from memory. It is the garbage collector's duty and responsibility to do so, and it does this automatically. The garbage collector will properly remove objects from memory when they become unreachable.

您可以将nil分配给地图和切片,因为nil是有效值(零值). struct类型的零值不是nil而是struct值,其中所有字段的值均为零.

You can assign nil to maps and slices because nil is a valid value (the zero value) for those types. The zero value for struct types is not nil but a struct value where all its fields have their zero values.

如果您想清除或覆盖结构值,则可以简单地分配另一个结构值最好是零值(一个空结构):

If you want to clear or overwrite the struct value, you may simply assign another struct value to it, preferably the zero value (an empty struct):

person1 := Person{name: "Name", age: 69}
// work with person1

// Clear person1:
person1 = Person{}

但是要知道,这不会释放person1分配的内存;如前所述,当无法访问时,它将由GC自动释放.

But know that this will not free memory allocated by person1; as wrote earlier, it will be freed automatically by the GC when it becomes unreachable.

nil也是指针类型的有效值(零值),因此如果person1将是指向Person(即*Person)的指针,则还可以将nil分配给它,例如:

nil is also a valid value (the zero value) for pointer types, so if person1 would be a pointer to Person (that is, *Person), you could also assign nil to it, e.g.:

person1 := &Person{name: "Name", age: 69}
// work with person1

// Clear person1:
person1 = nil

通过将指针设置为nil清除指针时,GC将再次处理该指向的对象.

When clearing a pointer by setting it to nil, the pointed object–again–will be taken care of by the GC.

有关垃圾收集器如何工作的更多详细信息,请参见

For more details about how the garbage collector works, see Cannot free memory once occupied by bytes.Buffer.

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

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