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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With