Skip to content

Instantly share code, notes, and snippets.

@paulsmith
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulsmith/2f1660a6a3183d812e4c to your computer and use it in GitHub Desktop.
Save paulsmith/2f1660a6a3183d812e4c to your computer and use it in GitHub Desktop.
assert in Go
package main
import (
"fmt"
"os"
"runtime"
)
func main() {
foo(0)
foo(1)
}
func foo(i int) {
_ = "blah"
assert(i == 0, "i must be zero")
_ = 1 + 2
}
func assert(cond bool, reason string) {
pc, file, line, ok := runtime.Caller(1)
if !ok && !cond {
// ???
panic(reason)
}
if !cond {
var fnName string
fn := runtime.FuncForPC(pc)
if fn != nil {
fnName = fn.Name()
}
if fnName != "" {
fmt.Fprintf(os.Stderr, "assert: %s:%d: %s: assertion failed: %s\n", file, line, fnName, reason)
} else {
fmt.Fprintf(os.Stderr, "assert: %s:%d: assertion failed: %s\n", file, line, reason)
}
os.Exit(1)
}
}
$ go run assert.go
assert: /tmp/assert.go:16: main.foo: assertion failed: i must be zero
exit status 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment