Golang os.Exit() Function with Examples

Golang | os.Exit() Function: Here, we are going to learn about the Exit() function of the os package with its usages, syntax, and examples.
Submitted by IncludeHelp, on November 16, 2021

os.Exit()

In the Go language, the os package provides a platform-independent interface to operating system (Unix-like) functionality. The Exit() function is an inbuilt function of the os package, it is used to exit from the current program with the given status code. The code 0 indicates success, non-zero an error. The program terminates immediately; deferred functions are not run. For portability, the status code should be in the range [0, 125].

It accepts one parameter (code int) and returns nothing.

Syntax:

func Exit(code int)

Parameter(s):

  • code - Status code.

Return Value:

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

Example 1:

// Golang program to demonstrate the
// example of Exit() function

package main

import (
	"fmt"
	"os"
)

func main() {
	fmt.Println("Hello, world!")
	os.Exit(0)
	fmt.Println("How, are you?")
}

Output:

Hello, world!

Example 2:

// Golang program to demonstrate the
// example of Exit() function

package main

import (
	"fmt"
	"os"
)

func main() {
	for i := 0; i < 10; i++ {
		fmt.Printf("[%d] Hello...\n", i)
		if i == 5 {
			fmt.Println("Bye...")
			// Exiting from the program
			// when value of i is 5
			os.Exit(0)
		}
	}
	fmt.Println("See you soon...")
}

Output:

[0] Hello...
[1] Hello...
[2] Hello...
[3] Hello...
[4] Hello...
[5] Hello...
Bye...

Golang os Package »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.