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

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>


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.

Tags:

Go