Golang os.Exit: How to Terminate Program in Go

Golang os.Exit() function is “used to immediately exits the program with a given status”. The Exit() function accepts a status code as an argument where code 0 suggests success and the non-zero code suggests an error.

Syntax

func Exit(code int)

Parameters

code: This parameter is the integer status code that will be returned to the operating system.

Return Value

The return type of the os.Exit() function nothing because it terminates the program.

Status codes

The status code 0 indicates an exit with no error and 1 with a general error. You can set the status code to whatever you want. Any other numerical value between 1 and 125 (golang) shows the program encountered an error.

Example 1: How to Use os.Exit() function

package main

import (
  "fmt"
  "os"
)

func main() {
  fmt.Println("We are the world!")
  os.Exit(0)
  fmt.Println("We are the children")
}

Output

We are the world!

Example 2: Using defer with Exit()

package main

import (
  "fmt"
  "os"
)

func main() {
  defer fmt.Println("Deferred function")
  fmt.Println("Starting program")
  os.Exit(3)
  fmt.Println("This line will not be executed")
}

Output

exit status 3

In this example, the os.Exit() function is used to instantly exit the program with a status code 3.

The defer statement is used to defer the execution of the fmt.Println(“Deferred function”) statement until the surrounding function has been completed.

However, since os.Exit() terminates the program immediately; the deferred function is not executed.

That’s it.

Related posts

Golang os.Chown()

Golang os.Chmod()

Golang os.Chdir()

Golang os.Lstat()

Golang os.Stat()