gontract is a require-ensure-library for Go that provides a contract-programming framework. To enable Design by Contract (DbC), it aims to bridge the "procedural gap" in Go by providing explicit Require and Ensure checks for preconditions and postconditions in Go code.
- Contract Decoupling: Separating safety logic from business logic.
- Safety Assertions: Provides immediate feedback upon contract violation during development.
| Function | Purpose | Usage |
|---|---|---|
Require(predicate bool, msg string) |
Precondition: Verifies caller-provided input. | Start of function. |
Ensure(predicate bool, msg string) |
Postcondition: Verifies function logic/return values. | Before return. |
A very natural pattern is to put posconditions into a defer statement like so:
func myfunc(args...) {
// postcondition(s):
defer func() {
Ensure(..)
..Ensure(..)
}()
// precondtions:
Require(..)
...
Require(..)
...
//implementation
...For interface-based designs, keep the interface itself plain and apply preconditions and postconditions in a wrapper implementation around the real implementation.
The companion package github.com/gontract/gontract/ifacewrap provides small
helpers for that style. Its declarative Requirements and Assurances run
through gontract.Require and gontract.Ensure automatically, so wrapper code
only needs to provide predicates and messages. See
cmd/examples/ifacewrap_division for a minimal example.