如何在Go中从func main函数中返回?

huangapple go评论71阅读模式
英文:

How do I return from func main in Go?

问题

我如何在C中像返回退出码一样从main函数返回?上下文: 我正在检查是否只有一个命令行参数,如果参数计数或参数无效,我将打印用法并返回错误状态码。

英文:

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.

答案1

得分: 33

Go使用Exit函数来实现这一功能。只需将状态码作为参数传递即可完成 如何在Go中从func main函数中返回?

要使用错误消息退出(exit(1)),您可以使用log.Fatal()/log.Fatalf()/log.Fatalln()函数:https://pkg.go.dev/log#Fatal

英文:

Go uses the Exit function for that. Just pass the status code as an argument and you're done 如何在Go中从func main函数中返回?

To exit(1) with an error message you can use log.Fatal()/log.Fatalf()/log.Fatalln(): https://pkg.go.dev/log#Fatal

答案2

得分: 23

正确答案在Matt Joiner的链接中。基本上是以下代码片段。必须确保代码的其余部分不会在任何地方调用os.Exit(),如flag.ExitOnError,log.Fatalf()等。

func main() { os.Exit(mainReturnWithCode()) }

func mainReturnWithCode() int {
    // 做一些事情,延迟函数等等。
    return exitcode // 适当的退出代码
}
英文:

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
}

huangapple
  • 本文由 发表于 2010年11月25日 22:48:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/4278293.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定