How do I return from main
with an exit code as I would in C? Context: I'm checking that there is a single command line argument, I will print usage and return an an error status code if the argument count, or argument is invalid.
Go uses the Exit function for that. Just pass the status code as an argument and you're done :)
The correct answer is in the link by Matt Joiner. Essentially the following snippet. One has to ensure that rest of the code does not call os.Exit() anywhere, like flag.ExitOnError, log.Fatalf(), etc.
func main() { os.Exit(mainReturnWithCode()) } func mainReturnWithCode() int { // do stuff, defer functions, etc. return exitcode // a suitable exit code }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With