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.
However it has print and println which does
pan开发者_如何学编程ic like print, aborts execution after printing
panicln like println, aborts execution after printing
Isnt that the same thing as an assert? Why would they claim the above but have panic? i can see it leading to the same problems but adding an error msg to the end of it which can easily be abused. Am i missing something?
No, it's not. panic is like "write then abort", while an assert is like "test and if it's false, write then abort". There's no way they can keep you from doing an assert-like statement anyways.
Apart from the obvious, that panic
does not check anything while assert
does, in Go you can use mechanics for error handling, even when a panic occurs.
If a package thinks something occurs that can not be recovered from it panics.
However, the package-user, the caller (parent level) may either want to inspect or log a panic and then continue to panic, or catch it to properly handle the case (for example, try again or then use a different package/function).
Also, an assert-abort does not call destructors or anything. A panic in Go though will still call even the functions you defer
will be executed, so everything is cleaned up.
So, as you can see, a panic will allow for a variety of cleanup-tasks in contrast to asserts. That’s what the quote you gave was pointing to.
For good information on defer, panic and recover, see the official blog post on them.
For one, in C, assert()
only aborts execution when in debug mode.
精彩评论