Functional options
Functional options are func(*Config) values passed to a constructor: NewServer(WithAddr(":8080"), WithTimeout(time.Second)). They keep the call readable when many settings are optional.
Detailed Explanation
A constructor with ten parameters is unreadable and has no defaults. A Config struct the caller must fill is better, but every call site names every field or starts from a zero that might be invalid. Functional options wrap the common case: NewServer() uses defaults, and each WithX changes one field.
The type. type Option func(*options) or type Option interface{ apply(*options) }. The function form is shorter. The interface form does not leak *options in the signature if you keep apply unexported, and it lets you pass values that are not functions. Dave Cheney's blog popularized the function form; the standard library's grpc and many others use it.
Apply in New. func New(opts ...Option) *Server allocates defaults, runs each option, then validates. Validation after options means WithAddr("") can still fail in one place. Return (*Server, error) if setup can fail.
When not to. Two or three parameters with clear names do not need options. A single Config struct is better when callers already build config from YAML and want to pass the whole thing. Options shine at the public constructor of a library where most users want defaults.
What it costs. Each WithX is a closure and an extra call. That is noise in a constructor you run once. Do not use options inside a per-request hot path as a substitute for a struct the compiler can see. Document the zero-value defaults next to New.
Code Examples
package server
import "time"
type options struct {
addr string
timeout time.Duration
}
type Option func(*options)
func WithAddr(addr string) Option {
return func(o *options) { o.addr = addr }
}
func WithTimeout(d time.Duration) Option {
return func(o *options) { o.timeout = d }
}
func New(opts ...Option) *Server {
o := options{addr: ":8080", timeout: time.Second}
for _, opt := range opts {
opt(&o)
}
return &Server{addr: o.addr, timeout: o.timeout}
}
type Server struct {
addr string
timeout time.Duration
}func main() {
_ = New(WithAddr(":443"), WithTimeout(5*time.Second))
}Common Gotchas
Options that run in order can override each other
last `WithAddr` wins. Document that.
Do not put required settings only in options
required values should be ordinary parameters so callers cannot omit them.
Keep `options` unexported
callers should not depend on the struct layout.
`Option` as an interface with unexported `apply` prevents fake options from othe
`Option` as an interface with unexported `apply` prevents fake options from other packages