Go语言的创造者写道:

Go doesn't provide assertions. They are undeniably convenient, but our experience has been that programmers use them as a crutch to avoid thinking about proper error handling and reporting. Proper error handling means that servers continue operation after non-fatal errors instead of crashing. Proper error reporting means that errors are direct and to the point, saving the programmer from interpreting a large crash trace. Precise errors are particularly important when the programmer seeing the errors is not familiar with the code.

你对此有什么看法?


当前回答

它们应该用于检测程序中的错误。不错的用户输入。

如果使用得当,它们并不邪恶。

其他回答

简短的回答:不,我相信断言可能有用

按照这种逻辑,断点也是邪恶的。

断言应该用作调试辅助,而不是其他。“邪恶”是当你试图使用它们而不是错误处理时。

断言的存在是为了帮助程序员检测和修复不可能存在的问题,并验证您的假设是否正确。

它们与错误处理无关,但不幸的是,一些程序员滥用它们,然后宣称它们是“邪恶的”。

与其说是坏事,不如说是适得其反。永久性错误检查和调试是分开的。Assert让人们认为所有的调试都应该是永久性的,使用过多会导致大量的可读性问题。在需要时,永久错误处理应该比这种方法更好,由于assert会导致自己的错误,因此这是一种非常值得怀疑的实践。

作为附加信息,go提供了一个内置函数panic。这可以用来代替assert。如。

if x < 0 {
    panic("x is less than 0");
}

Panic将打印堆栈跟踪,因此在某种程度上它具有assert的目的。

它们应该用于检测程序中的错误。不错的用户输入。

如果使用得当,它们并不邪恶。