有人能解释一下 os.Exit()
和 panic()
之间的主要区别以及它们在 Go 中的实际使用方式吗?
最佳答案
首先,每当您有“如何在实践中使用”的问题时,一个好的开始方法是 search Go 源代码(或任何足够大的 Go 代码库,真的)和 package docs寻找答案。
现在,os.Exit
和 panic
是完全不同的。 panic
在程序或其部分达到不可恢复状态时使用。
When
panic
is called, including implicitly for run-time errors such as indexing a slice out of bounds or failing a type assertion, it immediately stops execution of the current function and begins unwinding the stack of the goroutine, running any deferred functions along the way. If that unwinding reaches the top of the goroutine's stack, the program dies.
os.Exit
用于当您需要立即中止程序, 无法恢复或运行延迟清理语句,并且还会返回错误代码(其他程序可以用来报告发生的事情)。这在测试中很有用,当你已经知道一个测试失败后,另一个也会失败,所以你最好现在退出。这也可以在您的程序完成所有需要做的事情时使用,现在只需要退出,即在打印帮助消息之后。
大多数时候你不会使用 panic
(你应该返回一个 error
代替),而且你几乎不需要 os.Exit
在测试中的某些情况之外以及用于快速终止程序。
关于go - 何时使用 os.Exit() 和 panic()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28472922/