Keep a Go package contract stable
Use small interfaces, explicit errors, and compatibility tests.
Design for callers
Export only types and functions callers need. A package's public contract includes error categories, context behavior, zero-value usability, and whether a returned slice shares storage. Document these choices in examples. A convenience change can break callers if it alters mutation or error semantics.
Use errors as contracts
Wrap lower-level errors with %w when callers should inspect them. Define a sentinel or typed error only for distinctions callers can act on. Avoid comparing message text. When adding a method to an exported interface, remember that every implementation, including tests and downstream clients, must change.
if errors.Is(err, ErrNotFound) {
// Return a domain-specific result to the caller.
}
Test from another package
An external-package test exercises the API as a consumer sees it. Include examples for an empty input, a canceled context, and a recoverable error. Keep an internal test for implementation details only where it catches a real risk. A compatibility review should happen before renaming or removing exported symbols.
Check your understanding
Why can adding one method to an exported interface be a breaking change?
Show explanation
Every existing implementation must now provide that method, including downstream implementations outside your repository.
You can read for free. Create an account to save your progress.
Next lesson: Shut down a busy Go service safely →Try it at senior level
Propose a new option for a public Go package without breaking old callers. Write a compatibility matrix and two regression tests.
Check your work
Existing source still compiles, zero-value behavior is specified, and wrapped errors preserve documented errors.Is behavior.
Self-guided practice. This does not record assessed mastery.
Put this lesson into practice
A related activity in this module at mid level.
Try: Depend on an interface, not a structFurther reading
Primary references for this module. Check the current version when behavior or framework guidance may have changed.