Exit with error code in go?

后端 未结 5 1676
Happy的楠姐
Happy的楠姐 2021-02-01 12:21

What\'s the idiomatic way to exit a program with some error code?

The documentation for Exit says \"The program terminates immediately; deferred functions a

5条回答
  •  温柔的废话
    2021-02-01 13:03

    I do something along these lines in most of my real main packages, so that the return err convention is adopted as soon as possible, and has a proper termination:

    func main() {
        if err := run(); err != nil {
            fmt.Fprintf(os.Stderr, "error: %v\n", err)
            os.Exit(1)
        }
    }
    
    func run() error {
        err := something()
        if err != nil {
            return err
        }
        // etc
    }
    

提交回复
热议问题