How do I return from func main in Go?
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 a开发者_运维问答nd 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 :)
To exit(1)
with an error message you can use log.Fatal()
/log.Fatalf()
/log.Fatalln()
: https://pkg.go.dev/log#Fatal
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
}
精彩评论