本文介绍了等效于Java finalize方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Go中是否有类似java的finalize方法?如果我有一个类似

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

如何确保在对Object进行垃圾回收时,文件已关闭?

How can I make sure that when Object is garbage collected, the file is closed?

推荐答案

runtime.SetFinalizer iirc.但是它被认为是一件坏事,并且不能保证在程序退出之前就运行

runtime.SetFinalizer iirc. But its considered a bad thing and isn't guaranteed to run before program exit

如下所述,当前的 os 包已经在文件上调用了 runtime.SetFinalizer .但是,不应依赖 SetFinalizer .作为一个为什么的例子,我有一个类似于文件服务器的应用程序,但我忘了关闭打开的文件.通常,在GC将其选中并称为终结器之前,该过程通常会打开约300个打开的文件.

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方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 14:30