Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Go equivalent to assert() in C++?

Tags:

go

I'm looking for a condition check in Go which can terminate the program execution like assert in C++.

like image 238
Yixing Liu Avatar asked Nov 29 '17 17:11

Yixing Liu


People also ask

What is 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.

Should I use assert in C?

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.

What is assert in Golang?

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.

What is assert 0 C?

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.


2 Answers

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.

like image 152
maerics Avatar answered Sep 23 '22 23:09

maerics


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>

like image 24
Dan Jenson Avatar answered Sep 22 '22 23:09

Dan Jenson