This was discussed previously by the Go team, and the conclusion was not to support its support. Quoting minux :
Personally, I prefer a style in which the output of a program is handled exactly the same as a program crash. I believe that no matter how hard you try, your program may still fall under some unforeseen situations; for example, running out of memory can crash any Go Go program, and you can't do anything about it; therefore itβs better to develop them. If you follow this, you won't feel the need for atexit to clean up (because when your program crash, atexit will not work, so you just can't depend on it).
But you still have a few options:
CTRL + C Processing
If you want to do something when your program terminates CTRL + C ( SIGINT ), you can do this, see
Golang: is it possible to capture the Ctrl + C signal and run the cleanup function in the βdelayβ mode?
Object finalizer
Also note that you can register a finalizer function for a pointer value. When the garbage collector finds an unreachable block with an associated finalizer, it clears the association and runs f(x) in a separate version of goroutine.
You can register such a finalizer with runtime.SetFinalizer() , which may be enough for you, but note:
There is no guarantee that finalizers will work until the program is released, so they are usually only useful for freeing non-memory resources associated with an object during a long-term program.
See this 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") }
Exit ( Go to the site ):
2009/11/10 23:00:00 Finalizing &{Bob 20} 2009/11/10 23:00:01 Done