Documentation
¶
Overview ¶
Package assert provide a single function to emulate C-style asserts.
The goal of this package is to provide a call that will document and enforce preconditions, postconditions, and invariants in code. Failures should only result from program bugs. This package should not be used to replace proper error handling.
Assertions ¶
Each assertion documents that a predicate is true when the the assertion is executed. Depending on the build, that predicate might also be enforced (i.e. by terminating the program, or, more gently, by panicking). There are three types of assertion: (1) preconditions, which document conditions (specified as predicates) for calling a function, (2) postconditions, which document conditions at the end of a function, and (3) invariant, which specify conditions over a particular scope or for a type.
If the predicate for an assertion is false, this conditions indicates a bug in the code (as opposed to a transient or run-time error). When enforced, assertions are a debugging tool.
References ¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Assert ¶
Assert will panic if the value of predicate is false.
The panic's value will have type assert.Error. Note that the filename and line number are not recorded, but will be available if a stack trace is printed.
Example ¶
package main import ( "fmt" "gitlab.com/stone.code/assert" ) func main() { assert.Assert(true, "trivially true precondition") fmt.Println("OK") }
Output: OK
Example (Fail) ¶
package main import ( "fmt" "gitlab.com/stone.code/assert" ) func main() { defer func() { if r := recover(); r != nil { fmt.Println(r) } }() assert.Assert(false, "trivially false precondition") fmt.Println("OK") }
Output: assertion error: trivially false precondition
Example (Sqrt) ¶
package main import ( "fmt" "math" "gitlab.com/stone.code/assert" ) func main() { // The square root function in package math returns NaN if the value is // negative. If instead we wanted a precondition that the value was // non-negative, we could do the following (this is not a recommendation // to change the contract for math.Sqrt). sqrt := func(v float64) float64 { assert.Assert(v >= 0, "square root undefined for v<0") return math.Sqrt(v) } fmt.Printf("Sqrt of 1 is %0.1f\n", sqrt(1.0)) }
Output: Sqrt of 1 is 1.0
Types ¶
type Error ¶
type Error string
Error contains error information from a failed call to Assert.
func (Error) RuntimeError ¶
func (e Error) RuntimeError()
RuntimeError is a no-op function but serves to distinguish types that are run time errors from ordinary errors: a type is a run time error if it has a RuntimeError method.