问题描述
有没有像java中的finalize方法在Google中去?如果我有一个像
类型的结构体 type Foo struct {
f * os.File
.. ..
}
func(p * Foo)finalize(){
pfclose()
}
如何确保当Object被垃圾收集时,文件已关闭?
runtime.SetFinalizer
iirc。但它被认为是一件坏事,并不保证在程序退出前运行。编辑:如下所述,当前 os
包已经在文件上调用了 runtime.SetFinalizer
。但是,不应该依赖 SetFinalizer
。举个例子,我有一个类似文件服务器的应用程序,我忘记关闭打开的文件。这个过程通常会在GC收到它们并调用它们的终结器之前打开大约300个文件。
Is there any method like java finalize in google 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?
runtime.SetFinalizer
iirc. But its considered a bad thing and isn't guaranteed to run before program exit
EDIT: As mentioned below, the current os
package already calls runtime.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.
这篇关于谷歌去相当于Java finalize方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!