开发者

How do I return from func main in Go?

开发者 https://www.devze.com 2023-01-26 18:23 出处:网络
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 i

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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号