How to Use the Functional Options Pattern in Go

Use variadic functions that accept option functions to flexibly configure Go structs without bloating your constructor API.

The Functional Options Pattern in Go uses variadic functions accepting a slice of option functions to configure a struct without creating many constructors. Define an option type as a function that modifies a struct, then pass these functions to your constructor to apply settings selectively.

type Option func(*Config)

func WithTimeout(d time.Duration) Option {
    return func(c *Config) { c.Timeout = d }
}

func NewConfig(opts ...Option) *Config {
    c := &Config{Timeout: 5 * time.Second}
    for _, o := range opts {
        o(c)
    }
    return c
}

// Usage:
// cfg := NewConfig(WithTimeout(10 * time.Second))