问题描述
有人可以解释 os.Exit()
和 panic()
之间的关键区别以及它们如何使用在Golang的实践中?
首先,每当你有一个如何在实践中使用的问题,开始的方法是 Go源代码(或者任何足够大的Go代码库,真的),以及获取答案。
现在, os.Exit
和 panic
完全不同。 用于程序或其部分,
大多数时间你将不会使用 Could someone explain the key differences between 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. Now, Most of the time you won't use 这篇关于何时在Golang中使用os.Exit()和panic()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! os.Exit $如果展开到达goroutine堆栈顶部,程序就会死亡。当您需要立即中止程序时,使用c $ c>,不可能恢复或运行延迟清理语句,并返回错误代码(其他程序可用于报告发生了什么)。这在测试中非常有用,如果您已经知道在一次测试失败后另一次测试失败,那么您现在就可以退出。当你的程序完成了所有需要做的事情,并且现在只需要退出时,也就是在打印帮助信息后,这也可以使用。
panic
(您应该返回一个错误
),而且您几乎不需要 os.Exit
在某些情况下在测试和快速程序终止之外。os.Exit()
and panic()
and how they are used in practice in Golang?os.Exit
and panic
are quite different. panic
is used when the program, or its part, has reached an unrecoverable state.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
(you should return an error
instead), and you almost never need os.Exit
outside of some cases in tests and for quick program termination.