问题描述
有人可以解释os.Exit()
和panic()
之间的主要区别以及它们在Go中的实际使用方式吗?
Could someone explain the key differences between os.Exit()
and panic()
and how they are used in practice in Go?
推荐答案
首先,每当您遇到如何在实践中使用它"问题时,一个好的开始方法是 Go源代码(或实际上足够大的Go代码库)和以获取答案.
First of all, whenever you have a "how it is used in practice" question, a good way to start is to search the Go source code (or any big enough Go code base, really), and the package docs for answers.
现在,os.Exit
和panic
完全不同. panic
用于程序或其部分达到不可恢复的状态.
Now, os.Exit
and panic
are quite different. panic
is used when the program, or its part, has reached an unrecoverable state.
os.Exit
用于需要立即中止的程序,而无法恢复或运行延迟的清除语句,并且还返回错误代码(其他程序可以使用报告发生了什么).这在测试中很有用,当您已经知道一个测试失败后,另一个测试也会失败,因此您最好立即退出.当您的程序完成了它需要做的所有事情之后,现在只需要退出,即在打印帮助消息之后,也可以使用此功能.
os.Exit
is used when you need to abort the program immediately, with no possibility of recovery or running a deferred clean-up statement, and also return an error code (that other programs can use to report what happened). This is useful in tests, when you already know that after this one test fails, the other will fail as well, so you might as well just exit now. This can also be used when your program has done everything it needed to do, and now just needs to exit, i.e. after printing a help message.
在大多数情况下,您将不使用panic
(您应该返回error
),并且在某些情况下,在测试和快速终止程序中几乎不需要os.Exit
.
Most of the time you won't use panic
(you should return an error
instead), and you almost never need os.Exit
outside of some cases in tests and for quick program termination.
这篇关于何时使用os.Exit()和panic()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!