Google go equivalent to Java completion method

Is there any method like java finalize in google go? If I have a structure like

type Foo struct { f *os.File .... } func (p *Foo) finalize() { pfclose( ) } 

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

+6
go
source share
2 answers

runtime.SetFinalizer iirc. But it is considered bad and is not guaranteed to run before the program

EDIT: As mentioned below, the current os package already calls runtime.SetFinalizer in the files. However, SetFinalizer cannot rely on SetFinalizer . As an example, why I had an application similar to a file server when I forgot to close an open file. Typically, a process reaches 300 open files before the GC picks them up and calls them a finalizer.

+6
source share

You wouldn't do that in java either. The right thing to do in java is to have a finally block that closes it somewhere near where you opened.

To perform a cleanup, you must use a similar pattern to jump using the defer function. For example, if you did this (java):

 try { open(); // do stuff } finally { close(); } 

In go, you would do this:

 open(); defer close(); // do stuff 
+15
source share

All Articles