Паттерн Functional Options решает проблему конструкторов с большим числом опциональных параметров. Один конструктор принимает опции в виде функций.
type Server struct {
timeout time.Duration
logger *log.Logger
}
type Option func(*Server)
func WithTimeout(d time.Duration) Option {
return func(s *Server) { s.timeout = d }
}
func NewServer(opts ...Option) *Server {
s := &Server{timeout: 10 * time.Second}
for _, opt := range opts { opt(s) }
return s
}Использование: NewServer(WithTimeout(5*time.Second), WithLogger(log)). API остается обратно совместимым: новые опции добавляются без изменения сигнатуры.