Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return from func main in Go?

Tags:

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 and return an an error status code if the argument count, or argument is invalid.

like image 883
Matt Joiner Avatar asked Nov 25 '10 14:11

Matt Joiner


2 Answers

Go uses the Exit function for that. Just pass the status code as an argument and you're done :)

like image 168
Wolph Avatar answered Oct 31 '22 18:10

Wolph


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 } 
like image 37
Gurjeet Singh Avatar answered Oct 31 '22 18:10

Gurjeet Singh