Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a PHP function `die()` (or `exit()`) in Go?

Tags:

go

exit

die

In PHP, die() is used to stop running the script for preventing the unexpected behaviour. In Go, what is the idiomatic way to die a handle function? panic() or return?

like image 459
Casper Avatar asked Feb 06 '23 12:02

Casper


2 Answers

You should use os.Exit.

Exit causes the current program to exit with the given status code. Conventionally, code zero indicates success, non-zero an error. The program terminates immediately; deferred functions are not run.

package main

import (
    "fmt"
    "os"
)


func main() {
    fmt.Println("Start")
    os.Exit(1)
    fmt.Println("End")
}

Even, you can use panic, it's also stop normal execution but throw Error when execution stop.

The panic built-in function stops normal execution of the current goroutine. When a function F calls panic, normal execution of F stops immediately. Any functions whose execution was deferred by F are run in the usual way, and then F returns to its caller. To the caller G, the invocation of F then behaves like a call to panic, terminating G's execution and running any deferred functions. This continues until all functions in the executing goroutine have stopped, in reverse order. At that point, the program is terminated and the error condition is reported, including the value of the argument to panic. This termination sequence is called panicking and can be controlled by the built-in function recover.

package main

import "fmt"

func main() {
    fmt.Println("Start")
    panic("exit")
    fmt.Println("End")
}
like image 77
Pravin Mishra Avatar answered Feb 20 '23 14:02

Pravin Mishra


If you don't want to print a stack trace after exiting the program, you can use os.Exit. Also you are able to set a specific exit code with os.Exit.

Example (https://play.golang.org/p/XhDkKMhtpm):

package main

import (
    "fmt"
    "os"
)

func foo() {
    fmt.Println("bim")
    os.Exit(1)
    fmt.Println("baz")
}

func main() {
    foo()
    foo()
}

Also be aware, that os.Exit immediately stops the program and doesn't run any deferred functions, while panic() does. See https://play.golang.org/p/KjGFZzTrJ7 and https://play.golang.org/p/Q4iciT35kP.

like image 39
svenwltr Avatar answered Feb 20 '23 13:02

svenwltr