Implement the Options Pattern by defining a function type that modifies a configuration struct, then pass a variadic slice of these functions to your constructor.
type Config struct {
Timeout time.Duration
Verbose bool
}
type Option func(*Config)
func WithTimeout(d time.Duration) Option {
return func(c *Config) { c.Timeout = d }
}
func WithVerbose() Option {
return func(c *Config) { c.Verbose = true }
}
func NewClient(opts ...Option) *Client {
cfg := &Config{Timeout: 5 * time.Second}
for _, opt := range opts {
opt(cfg)
}
return &Client{cfg: cfg}
}