Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of java finalize method

Tags:

go

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?

like image 974
Nyan Avatar asked Jan 08 '11 23:01

Nyan


1 Answers

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):

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

In go, you'd do this:

open();
defer close();
// do stuff
like image 173
Dustin Avatar answered Oct 14 '22 08:10

Dustin