Last active
August 29, 2015 14:26
-
-
Save paulsmith/2f1660a6a3183d812e4c to your computer and use it in GitHub Desktop.
assert in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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