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
?
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())
}