Yixing Liu
Yixing Liu

Reputation: 2429

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

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

Upvotes: 57

Views: 43741

Answers (3)

guettli
guettli

Reputation: 27855

I use this generic Go function in tests:

func assertEqual[T comparable](t *testing.T, expected T, actual T) {
    t.Helper()
    if expected == actual {
        return
    }
    t.Errorf("expected (%+v) is not equal to actual (%+v)", expected, actual)
}

func assertSliceEqual[T comparable](t *testing.T, expected []T, actual []T) {
    t.Helper()
    if len(expected) != len(actual) {
        t.Errorf("expected (%+v) is not equal to actual (%+v): len(expected)=%d len(actual)=%d",
            expected, actual, len(expected), len(actual))
    }
    for i := range expected {
        if expected[i] != actual[i] {
            t.Errorf("expected[%d] (%+v) is not equal to actual[%d] (%+v)",
                i, expected[i],
                i, actual[i])
        }
    }
}

Some people use testify but I prefer to copy+paste above function.

Upvotes: 1

Dan Jenson
Dan Jenson

Reputation: 1041

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>

Upvotes: 5

maerics
maerics

Reputation: 156444

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.

Upvotes: 60

Related Questions