Defaults and Validation
Set sensible defaults.
Set Sensible Defaults
A robust constructor starts from good defaults, then lets options override them. This avoids the zero-value trap entirely.
Initialize Before Applying
Build the config with defaults first, then apply the options on top.
package main
import "fmt"
type Server struct {
Port int
Timeout int
}
type Option func(*Server)
func WithPort(p int) Option { return func(s *Server) { s.Port = p } }
func NewServer(opts ...Option) *Server {
s := &Server{Port: 8080, Timeout: 30}
for _, o := range opts { o(s) }
return s
}
func main() {
fmt.Printf("%+v\n", *NewServer())
fmt.Printf("%+v\n", *NewServer(WithPort(9000)))
}All lessons in this course
- The Problem with Many Params
- Option Functions
- Building a Flexible API
- Defaults and Validation