相当于java的finalize方法
Go中有类似java Finalize的方法吗?如果我有一个类型结构,例如
type Foo struct {
f *os.File
....
}
func (p *Foo) finalize() {
p.f.close( )
}
如何确保当对象被垃圾收集时,文件已关闭?
Is there any method like java finalize in Go? If I've a type struct like
type Foo struct {
f *os.File
....
}
func (p *Foo) finalize() {
p.f.close( )
}
How can I make sure that when Object is garbage collected, the file is closed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 java 中你也不会这样做。在 java 中正确的做法是使用一个
finally
块来将其关闭在您打开的位置附近。您可以在 go 中使用类似的模式和
defer
函数来进行清理。例如,如果你这样做(java):在go中,你会这样做:
You wouldn't do that in java, either. The correct thing to do in java is to have a
finally
block that closes it somewhere near where you opened up.You'd use a similar pattern in go with a
defer
function to do the cleanup. For example, if you did this (java):In go, you'd do this:
runtime.SetFinalizer
iirc。但它被认为是一件坏事,并且不能保证在程序退出之前运行编辑:如下所述,当前的 os 包已经在文件上调用了 runtime.SetFinalizer 。但是,不应依赖
SetFinalizer
。作为一个例子,我有一个类似文件服务器的应用程序,我忘记关闭打开的文件。在 GC 拾取它们并调用其终结器之前,该过程通常会打开大约 300 个文件。runtime.SetFinalizer
iirc. But its considered a bad thing and isn't guaranteed to run before program exitEDIT: As mentioned below, the current
os
package already callsruntime.SetFinalizer
on files. However,SetFinalizer
shouldn't be relied upon. As an example of why, I had a file-server-like application where I forgot to close open file. The process would usually get to about 300 open files before the GC picked them up and called their finalizer.