Go

Functional Options Pattern

admin by @admin ADMIN
3d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Replace giant config structs with a variadic list of `Option` functions. Lets you add optional parameters later without breaking existing callers. The standard Go API design for constructors.
Go
Raw
package main

import (
    "fmt"
    "time"
)

type Server struct {
    addr    string
    timeout time.Duration
    tls     bool
    logger  func(string)
}

type Option func(*Server)

func WithTimeout(d time.Duration) Option { return func(s *Server) { s.timeout = d } }
func WithTLS()                  Option   { return func(s *Server) { s.tls = true } }
func WithLogger(fn func(string)) Option  { return func(s *Server) { s.logger = fn } }

func NewServer(addr string, opts ...Option) *Server {
    s := &Server{
        addr:    addr,
        timeout: 30 * time.Second,                 // defaults
        logger:  func(string) {},                  // no-op
    }
    for _, opt := range opts { opt(s) }
    return s
}

func main() {
    srv := NewServer(":8080",
        WithTimeout(5*time.Second),
        WithTLS(),
        WithLogger(func(msg string) { fmt.Println("LOG:", msg) }),
    )
    fmt.Printf("%+v\n", srv)
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.