Exit with error code in go?

后端 未结 5 1675
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 12:42

    As mentioned by fas, you have func Exit(exitcode int) from the os package.

    However, if you need the defered function to be applied, you always can use the defer keyword like this:

    http://play.golang.org/p/U-hAS88Ug4

    You perform all your operation, affect a error variable and at the very end, when everything is cleaned up, you can exit safely.

    Otherwise, you could also use panic/recover: http://play.golang.org/p/903e76GnQ-

    When you have an error, you panic, end you cleanup where you catch (recover) it.

提交回复
热议问题