shutdown hook - Is there something like finally() in Go just opposite to what init()? -


is there in go opposite init() inside package?

this discussed before go team, , conclusion not add support it. quoting minux:

personally, prefer style program exit handled same program crash. believe no matter how hard try, program can still crash under unforeseen situations; example, memory shortage can bring well-behave go program crash, , there nothing can it; it's better design them. if follow this, won't feel need atexit clean (because when program crash, atexit won't work, can't depend on it).

but still have options:

handling ctrl+c

if want when program terminated ctrl+c (sigint), can so, see:

golang: possible capture ctrl+c signal , run cleanup function, in "defer" fashion?

object finalizer

also note can register finalizer function pointer value. when garbage collector finds unreachable block associated finalizer, clears association , runs f(x) in separate goroutine.

you can register such finalizer runtime.setfinalizer() might enough you, note:

there no guarantee finalizers run before program exits, typically useful releasing non-memory resources associated object during long-running program.

see example:

type person struct {     name string     age  int }  func main() {     go func() {         p := &person{"bob", 20}         runtime.setfinalizer(p, func(p2 *person) {             log.println("finalizing", p2)         })         runtime.gc()     }()      time.sleep(time.second * 1)     log.println("done") } 

output (go playground):

2009/11/10 23:00:00 finalizing &{bob 20} 2009/11/10 23:00:01 done 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - Bypass Geo Redirect for specific directories -

php - .htaccess mod_rewrite for dynamic url which has domain names -