Typically, an exit code of 0 means that the program executes successfully. Any other numerical value between 1 and 125 (golang) shows the program encountered an error.
We can use the os package to exit a function with a specific exit code in Go. Follow this short to understand how to work with the exit() function.
The Basics – Exit()
The exit method from the os package helps us terminate a program with a specific error code. The syntax is as shown:
The function takes an exit code between 0 and 125 as the argument.
The program will die instantly if it encounters the exit() function. This means that delayed functions will not run.
Example – Error
In the example below, the program terminates the program after the exit() function.
import (
"fmt"
"os"
)
funcmain() {
fmt.Println("I run")
os.Exit(5)
fmt.Println("I never run")
}
If we run the code above, we will execute the code before the exit() method. The program then quits and prints an exit message as:
I run
exit status 5
As mentioned, an error code above 0 indicates an error. However, keep in mind reserved exit codes as shown in the resource below:
https://tldp.org/LDP/abs/html/exitcodes.html
Example – Success
To exit a program without an error, you can set the exit code of the program to 0, as shown in the example below:
import (
"fmt"
"os"
)
funcmain() {
fmt.Println("I run")
os.Exit(0)
fmt.Println("I never run")
}
Regardless of the error code, any code after the exit() method does not run.
Conclusion
This short guide covered how to use the exit() method from the os package. Using this method, you can axe 😊 a program with an exit status.
Thanks for reading!