« Back to Index

Go: defer with os.Exit(N)

View original Gist on GitHub

Tags: #go

Go defer with os.Exit(N).go

package main

import (
	"fmt"
	"os"
	"runtime"
)

/*
Goexit terminates the goroutine that calls it. No other goroutine is affected. Goexit runs all deferred calls before terminating the goroutine. Because Goexit is not a panic, any recover calls in those deferred functions will return nil.

Calling Goexit from the main goroutine terminates that goroutine without func main returning. Since func main has not returned, the program continues execution of other goroutines. If all other goroutines exit, the program crashes.

https://golang.org/pkg/runtime/#Goexit
*/

func main() {
	defer os.Exit(0)
	fmt.Println("Hello, playground")
	defer fmt.Println("end")
	runtime.Goexit() // instead of os.Exit(1)
}