Search code examples
goexitdie

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


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?


Solution

  • 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")
    }