Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Return exit status code in Go (Golang)

Posted on April 13, 2023April 13, 2023 by admin

Table of Contents

  • Overview
  • Code

Overview

‘os’ package of golang provides an Exit function that can be used to exit the current program with a status code.

  • Status code zero means success
  • Non-zero status code means an error.

Once this function is called the program exits immediately. Even the deferred functions are not called.

Also to note that status code should be in the range [0, 125]

func Exit(code int)

Let’s see a working code

Code

package main
import (
"fmt"
"os"
)
func main() {
success := true
if success {
fmt.Println("Success")
os.Exit(0)
} else {
fmt.Println("Failure")
os.Exit(1)
}
}

Output

Try setting success to false to see a different output

Success
$ echo $?
0
  • code
  • exit
  • go
  • golang
  • os
  • status
  • Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2023 Welcome To Golang By Example | Design: Web XP