I'm looking for a condition check in Go which can terminate the program execution like assert in C++.
In the C Programming Language, assert is a macro that is designed to be used like a function. It checks the value of an expression that we expect to be true under normal circumstances. If expression is a nonzero value, the assert macro does nothing.
You should only use assert to check for situations that "can't happen", e.g. that violate the invariants or postconditions of an algorithm, but probably not for input validation (certainly not in libraries). When detecting invalid input from clients, be friendly and return an error code.
Type assertions in Golang provide access to the exact type of variable of an interface. If already the data type is present in the interface, then it will retrieve the actual data type value held by the interface. A type assertion takes an interface value and extracts from it a value of the specified explicit type.
assert(0) or assert(false) is usually used to mark unreachable code, so that in debug mode a diagnostic message is emitted and the program is aborted when the supposedly unreachable is actually reached, which is a clear signal that the program isn't doing what we think it is.
As mentioned by commenters, Go does not have assertions.
A comparable alternative in Go is the built-in function panic(...)
, gated by a condition:
if condition { panic(err) }
This article titled "Defer, Panic, and Recover" may also be informative.
I actually use a little helper:
func failIf(err error, msg string) { if err != nil { log.Fatalf("error " + msg + ": %v", err) } }
And then in use:
db, err := sql.Open("mysql", "my_user@/my_database") defer db.Close() failIf(err, "connecting to my_database")
On failure it generates:
error connecting to my_database: <error from MySQL/database>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With