How to exit a go program honoring deferred calls?

marcio picture marcio · Dec 24, 2014 · Viewed 21.8k times · Source

I need to use defer to free allocations manually created using C library, but I also need to os.Exit with non 0 status at some point. The tricky part is that os.Exit skips any deferred instruction:

package main

import "fmt"
import "os"

func main() {

    // `defer`s will _not_ be run when using `os.Exit`, so
    // this `fmt.Println` will never be called.
    defer fmt.Println("!")
    // sometimes ones might use defer to do critical operations
    // like close a database, remove a lock or free memory

    // Exit with status code.
    os.Exit(3)
}

Playground: http://play.golang.org/p/CDiAh9SXRM stolen from https://gobyexample.com/exit

So how to exit a go program honoring declared defer calls? Is there any alternative to os.Exit?

Answer

Rob Napier picture Rob Napier · Dec 24, 2014

Just move your program down a level and return your exit code:

package main

import "fmt"
import "os"

func doTheStuff() int {
    defer fmt.Println("!")

    return 3
}

func main() {
    os.Exit(doTheStuff())
}