Return from main with exit status and run deferred functions

How can i return from main function with a non zero status code
and before returning run deferred functions.

os.Exit() allows to set a non zero status code but it exits the program
immediately and deferred functions are not run.

I don’t know if you can. Why not do this:

func main() {
    if err := main2(); err != nil {
        os.Exit(1)
        // or panic(err)?
    }
}

func main2() error {
    defer something()
    return nil
}
package main

import (
	"fmt"
	"os"
)

func main() {
	// the last deferred function to run
	var exitCode int
	defer func() { os.Exit(exitCode) }()

	defer func() { fmt.Println("other deferred functions") }()

	if err := fmt.Errorf("an error"); err != nil {
		fmt.Println(err)
		exitCode = 42
		return
	}
}

https://play.golang.org/p/9D7zXuycmJm

an error
other deferred functions

Program exited: status 42.
1 Like

because my program only contain the main function.

this doesn’t look good. There should be a much simpler way of doing this.

This actually looks like a really reasonable solution. Especially given that main() should not have much more code that this in it anyway.

If the example showed that the second anonymous defer func() called the main logic in another like you do with say, Cobra CLI this is would then show a very idiomatic solution indeed!

Ah! I was facing this issue but fixed now. Thanks!