The Functional Options Pattern

The Functional Options Pattern in Go: Imagine a cafe till with one button per possible drink. Small oat latte. Small oat latte with an extra shot.

The Analogy: The Coffee Order

Imagine a cafe till with one button per possible drink. Small oat latte. Small oat latte with an extra shot. Medium oat latte with an extra shot and no foam. The buttons multiply far faster than the menu does, and the day the cafe adds almond milk the whole board has to double. That till is the API that grows NewClient, then NewClientWithTimeout, then NewClientWithTimeoutAndRetries, and eventually a function whose name is longer than its body.

The other extreme is a form where every box is mandatory. Size, milk, shots, syrup, temperature, lid. A customer who wants a plain black coffee still fills in six boxes, and when the cafe adds a seventh the printed forms are all invalid. That is a positional parameter list, or a config struct whose zero value means nothing useful, and it is why nobody enjoys calling New(addr, 5*time.Second, 3, nil, false, true) - a call in which nothing is named and everything is a guess.

What real cafes do is name the drink and then say only what differs. "Latte. Oat milk, extra shot." The base is a complete and sensible drink on its own. Each modifier is small and independent, the order barely matters, and next month's new syrup does not invalidate anybody's usual order. The customer states deviations from a good default rather than reconstructing the drink from parts.

Functional options are that idea spelled in Go. The constructor takes the genuinely required arguments plus ...Option, where an Option is a function that adjusts a configuration. Defaults live in exactly one place, callers name only what they want changed, and the option list can grow for a decade without breaking a single existing call. The cost is machinery: a type, a loop, and one small exported function per setting. Knowing when that cost is worth paying - and when a plain struct with exported fields is the better answer - is most of what this lesson is about.


Syntax or Core Structure

Required arguments stay as parameters. Everything optional becomes an Option.

// server/server.go
package server

import (
	"errors"
	"fmt"
	"log/slog"
	"time"
)

type Server struct {
	addr    string // required, so it is a plain parameter
	timeout time.Duration
	retries int
	logger  *slog.Logger
}

// Option adjusts a Server during construction. Options are applied in the
// order given, so a later option overrides an earlier one.
type Option func(*Server)

func WithTimeout(d time.Duration) Option {
	return func(s *Server) { s.timeout = d }
}

func WithRetries(n int) Option {
	return func(s *Server) { s.retries = n }
}

func WithLogger(l *slog.Logger) Option {
	return func(s *Server) { s.logger = l }
}

func New(addr string, opts ...Option) (*Server, error) {
	if addr == "" {
		return nil, errors.New("server: addr is required")
	}
	s := &Server{
		addr:    addr,
		timeout: 5 * time.Second, // every default lives here and nowhere else
		retries: 3,
		logger:  slog.Default(),
	}
	for _, opt := range opts {
		opt(s)
	}
	// Validate AFTER applying, so no option can smuggle a bad value past.
	if s.timeout <= 0 {
		return nil, fmt.Errorf("server: timeout must be positive, got %v", s.timeout)
	}
	if s.retries < 0 {
		return nil, fmt.Errorf("server: retries cannot be negative, got %d", s.retries)
	}
	return s, nil
}

func (s *Server) String() string {
	return fmt.Sprintf("addr=%s timeout=%v retries=%d", s.addr, s.timeout, s.retries)
}

Five calls that show every rule at once:

func main() {
	a, _ := server.New("localhost:8080")
	fmt.Println("defaults: ", a)

	b, _ := server.New("localhost:9090",
		server.WithTimeout(30*time.Second),
		server.WithRetries(0), // an explicit zero, distinguishable from unset
	)
	fmt.Println("tuned:    ", b)

	c, _ := server.New("localhost:7070",
		server.WithTimeout(1*time.Second),
		server.WithTimeout(2*time.Second), // later wins
	)
	fmt.Println("last wins:", c)

	if _, err := server.New("localhost:6060", server.WithTimeout(-1)); err != nil {
		fmt.Println("rejected:", err)
	}
	if _, err := server.New(""); err != nil {
		fmt.Println("rejected:", err)
	}
}

Output:

defaults:  addr=localhost:8080 timeout=5s retries=3
tuned:     addr=localhost:9090 timeout=30s retries=0
last wins: addr=localhost:7070 timeout=2s retries=3
rejected: server: timeout must be positive, got -1ns
rejected: server: addr is required

WithRetries(0) is the detail worth pausing on. Zero is a meaningful value for retries and also the zero value of int, so a config struct cannot tell "the caller asked for none" from "the caller said nothing" without resorting to a *int. An option can, because being called at all is the signal.


Technical Depth: Three Shapes, and When Not to Bother

The three shapes of Option

ShapeDeclarationWhat it buys
Plain mutatortype Option func(*config)The least machinery. An option cannot report a problem
Fallibletype Option func(*config) errorValidation lives in the option, so the error names the option
Interfacetype Option interface{ apply(*config) }A closed set, and options you can inspect before applying

The fallible form moves each check next to the value it checks:

type Option func(*Server) error

func WithTimeout(d time.Duration) Option {
	return func(s *Server) error {
		if d <= 0 {
			return fmt.Errorf("WithTimeout: must be positive, got %v", d)
		}
		s.timeout = d
		return nil
	}
}

The message now says WithTimeout, which points at the caller's line rather than at a field name they may never have heard of. The price is a return nil on every option and error handling in the loop - and the reward, with errors.Join, is reporting every bad option in one pass instead of stopping at the first.

The interface form is what large libraries use:

type Option interface{ apply(*Server) }

type timeoutOption time.Duration

func (t timeoutOption) apply(s *Server) { s.timeout = time.Duration(t) }

func WithTimeout(d time.Duration) Option { return timeoutOption(d) }

Because apply is unexported, no other package can implement Option. Your option set is closed, so you can add a field, change how an option behaves, or start deduplicating options without anybody's home-made Option breaking. It also makes options inspectable: a concrete type per option means you can type-switch over them, drop duplicates, or log the configuration that was requested. This is how gRPC and OpenTelemetry declare their options, and the reason is API stability rather than elegance.

Put the settings on an unexported config, not on the live type

The first example applied options straight to *Server, which is fine for four fields and dangerous once Server holds real machinery. An option handed a *Server can reach a mutex, a connection pool or a running listener. Separating the two costs three lines:

type config struct {
	timeout time.Duration
	retries int
}

type Option func(*config)

func New(addr string, opts ...Option) (*Server, error) {
	cfg := config{timeout: 5 * time.Second, retries: 3}
	for _, o := range opts {
		o(&cfg)
	}
	// validate cfg here, then build the Server from it
	return &Server{addr: addr, cfg: cfg, pool: newPool()}, nil
}

Now an option can only touch settings, the config is a plain copyable value you can construct directly in tests, and Server's fields are free to change shape without touching a single option.

Options are just functions, so test them one at a time

func TestWithTimeout(t *testing.T) {
	var c config
	WithTimeout(2 * time.Second)(&c) // build it, then call it
	if c.timeout != 2*time.Second {
		t.Errorf("timeout = %v, want 2s", c.timeout)
	}
}

That double call - WithTimeout(d)(&c) - is the tell. An Option is a closure over its argument and nothing more, which is why the pattern needs no framework and why each option is trivially unit-testable without constructing the real object.

When a plain struct is the better answer

The pattern is fashionable enough that it gets used where it costs more than it returns. Note that a struct literal with field names is already "name only what differs": &http.Server{Addr: ":8080"} sets one field out of a dozen and reads beautifully. So the real advantages of options over an exported struct are narrower than their popularity suggests. There are five, and they are worth memorising:

  • You can distinguish unset from zero without pointers, as WithRetries(0) showed.
  • One option can set several fields at once, or derive one field from another.
  • The config can stay unexported, so its shape is not part of your API and can change freely.
  • An option can fail with a targeted error naming itself.
  • The object is immutable after construction, because there are no exported fields to write to later.

If none of those five apply, an exported struct is less code for both you and your callers.

SituationReach for
Two or three settings, unlikely to growPlain parameters, or a small struct
Many settings, most callers happy with defaults, public API that must not breakFunctional options
Callers build the configuration from a file, flags or environmentAn exported Config with json tags and New(cfg Config)
A library others extend over years, where the option set must stay closedThe interface form of Option

The standard library is the evidence for the sceptical side. http.Server, http.Client, tls.Config and json.Encoder are all structs with exported fields and useful zero values, and they have survived more than a decade of additions without a single WithX function. Meanwhile gRPC, OpenTelemetry and the AWS SDK use options everywhere. The dividing line is not old versus modern taste: struct literals win when the caller assembles configuration as data, and options win when a library must keep adding settings for years, or when settings need validating and combining rather than merely assigning. Offering both mechanisms for the same field is the one choice that is clearly wrong, because now two sources of truth can disagree.

Composing options, and the ordering hazard

Because an option is a function over the config, a group of options is just another option:

// Aggressive is a preset. Because options apply in order, a preset placed
// AFTER an explicit option will silently overwrite it.
func Aggressive() Option {
	return func(c *config) {
		WithTimeout(500 * time.Millisecond)(c)
		WithRetries(8)(c)
	}
}

That comment is the whole hazard. New(addr, WithTimeout(time.Minute), Aggressive()) gives you 500 milliseconds and no warning, because the last write wins and a preset writes several fields. Document the ordering rule in the Option type's doc comment, put presets first by convention, and resist writing options that read the config as well as writing it - an option whose behaviour depends on what came before it turns the option list into a program.


Real World Example: A Cache Whose Clock You Can Replace

An expiring cache with a size limit, an eviction hook, and one option that exists purely so the thing can be tested.

// cache/cache.go
package cache

import (
	"errors"
	"fmt"
	"sync"
	"time"
)

type entry struct {
	value   string
	expires time.Time
}

type config struct {
	maxEntries int
	ttl        time.Duration
	now        func() time.Time
	onEvict    func(key, reason string)
}

// Option configures a Cache. Options are applied in the order given, so a
// later option overrides an earlier one.
type Option func(*config) error

func WithMaxEntries(n int) Option {
	return func(c *config) error {
		if n <= 0 {
			return fmt.Errorf("WithMaxEntries: must be positive, got %d", n)
		}
		c.maxEntries = n
		return nil
	}
}

func WithTTL(d time.Duration) Option {
	return func(c *config) error {
		if d <= 0 {
			return fmt.Errorf("WithTTL: must be positive, got %v", d)
		}
		c.ttl = d
		return nil
	}
}

// WithClock replaces time.Now. Its real purpose is deterministic tests,
// which is the only reason it exists.
func WithClock(now func() time.Time) Option {
	return func(c *config) error {
		if now == nil {
			return errors.New("WithClock: nil clock")
		}
		c.now = now
		return nil
	}
}

func WithEvictionHook(f func(key, reason string)) Option {
	return func(c *config) error {
		if f == nil {
			return errors.New("WithEvictionHook: nil hook")
		}
		c.onEvict = f
		return nil
	}
}

type Cache struct {
	cfg config
	mu  sync.Mutex
	m   map[string]entry
}

func New(opts ...Option) (*Cache, error) {
	cfg := config{
		maxEntries: 128,
		ttl:        time.Minute,
		now:        time.Now,
		onEvict:    func(string, string) {}, // never nil, so no nil check later
	}
	var errs []error
	for _, o := range opts {
		if err := o(&cfg); err != nil {
			errs = append(errs, err) // collect, do not stop
		}
	}
	if err := errors.Join(errs...); err != nil {
		return nil, fmt.Errorf("cache.New: %w", err)
	}
	return &Cache{cfg: cfg, m: make(map[string]entry, cfg.maxEntries)}, nil
}

The behaviour, with every time comparison going through c.cfg.now:

func (c *Cache) Put(key, value string) {
	c.mu.Lock()
	defer c.mu.Unlock()
	if _, exists := c.m[key]; !exists && len(c.m) >= c.cfg.maxEntries {
		c.evictOldestLocked()
	}
	c.m[key] = entry{value: value, expires: c.cfg.now().Add(c.cfg.ttl)}
}

func (c *Cache) Get(key string) (string, bool) {
	c.mu.Lock()
	defer c.mu.Unlock()
	e, ok := c.m[key]
	if !ok {
		return "", false
	}
	if !c.cfg.now().Before(e.expires) {
		delete(c.m, key)
		c.cfg.onEvict(key, "expired")
		return "", false
	}
	return e.value, true
}

// evictOldestLocked drops the entry expiring soonest, breaking ties by key
// so the victim never depends on map iteration order.
func (c *Cache) evictOldestLocked() {
	var victim string
	var best time.Time
	for k, e := range c.m {
		if victim == "" || e.expires.Before(best) || (e.expires.Equal(best) && k < victim) {
			victim, best = k, e.expires
		}
	}
	if victim != "" {
		delete(c.m, victim)
		c.cfg.onEvict(victim, "capacity")
	}
}

And the caller, with a clock it advances by hand:

func main() {
	// A clock we control, so this program prints the same thing forever.
	base := time.Date(2026, 3, 4, 12, 0, 0, 0, time.UTC)
	var elapsed time.Duration
	clock := func() time.Time { return base.Add(elapsed) }

	var evicted []string
	c, err := cache.New(
		cache.WithMaxEntries(2),
		cache.WithTTL(10*time.Second),
		cache.WithClock(clock),
		cache.WithEvictionHook(func(key, reason string) {
			evicted = append(evicted, key+":"+reason)
		}),
	)
	if err != nil {
		panic(err)
	}

	c.Put("a", "apple")
	elapsed += 2 * time.Second
	c.Put("b", "banana")
	elapsed += 2 * time.Second
	c.Put("c", "cherry") // at capacity, so the soonest-expiring entry goes

	for _, k := range []string{"a", "b", "c"} {
		v, ok := c.Get(k)
		fmt.Printf("get %s -> %q %v\n", k, v, ok)
	}

	elapsed += 9 * time.Second
	fmt.Println("after 13s:")
	for _, k := range []string{"b", "c"} {
		v, ok := c.Get(k)
		fmt.Printf("get %s -> %q %v\n", k, v, ok)
	}
	fmt.Println("evicted:", evicted)

	// Two bad options at once: both are reported.
	_, err = cache.New(cache.WithMaxEntries(0), cache.WithTTL(-time.Second))
	fmt.Println("error:", err)
}

Output:

get a -> "" false
get b -> "banana" true
get c -> "cherry" true
after 13s:
get b -> "" false
get c -> "cherry" true
evicted: [a:capacity b:expired]
error: cache.New: WithMaxEntries: must be positive, got 0
WithTTL: must be positive, got -1s

Four settings, four independent decisions, made in five lines with no ordering requirement between them. Add a fifth setting next month and you add one exported function; every existing call site keeps compiling, unchanged. The defaults sit in exactly one place - the config literal at the top of New - which is the largest practical win over asking each caller to fill in a struct, because it means "what happens if I say nothing" has a single readable answer that cannot drift between call sites.

WithClock is the option that pays for the whole pattern. Without it, testing expiry means time.Sleep(10 * time.Second) in your test suite, and the output above would differ on every run. With it, elapsed += 9 * time.Second moves the world forward instantly and the program is reproducible forever. Notice what would have happened had the cache been configured by an exported struct: Now func() time.Time would be a permanent, public, documented field of the cache, and every caller would wonder whether they were supposed to set it. As an option over an unexported config, the same seam costs the public API nothing.

The fallible form earned its keep in the last two lines. Both bad options were reported together, and each message names the option that failed rather than the field it writes, so a caller can find the offending line immediately. One practical detail to know before you copy this: errors.Join separates its messages with newlines, so that final error prints across two lines. That is ideal for a startup failure a human will read, and it is worth handling deliberately if the message is going into a one-line-per-event log format.

Two details connect back through the course. evictOldestLocked breaks ties by key so the victim never depends on map iteration order - the same determinism discipline the maps lesson insisted on, applied here to a decision rather than to printed output. And config is unexported, so no option can reach mu or m; options touch settings and nothing else. That is the closing idea of this module, and of the course. Composition decides what behaviour a type has, a registry decides which behaviours a program contains, and options let each one be tuned by its caller without the library ever breaking them. All three are built from interfaces, first-class functions and plain structs - nothing that was not already in the language on the first page.


Common Mistakes

  1. Offering an exported Config struct and options for the same fields. Now there are two sources of truth and they can disagree. Pick one mechanism per setting and document it.
  1. Hiding required arguments in options. New(WithAddr("...")) lets a caller omit the address and find out at runtime. Anything mandatory belongs in the parameter list, where the compiler enforces it.
  1. Validating before applying options, or not at all. Checks placed before the loop see only the defaults, which always pass. Validate after every option has run, so the value you check is the value you will use.
  1. Handing options the live object. An Option func(*Server) can reach a mutex, a pool or a running listener. Apply options to an unexported config and build the real object from it.
  1. A plain-mutator option that silently accepts nonsense. WithTimeout(-1) with no validation gives you a server that never succeeds. Either validate in the constructor after the loop, or use the fallible form so the error names the option.
  1. Letting a nil function or pointer through. WithLogger(nil) or WithEvictionHook(nil) turns into a nil dereference much later, far from the call that caused it. Reject nil at the option, and give hooks a do-nothing default so no call site needs a nil check.
  1. Stopping at the first bad option. Returning immediately means a caller with three mistakes fixes them one build at a time. Collect into a slice and errors.Join them.
  1. Presets placed after explicit options. A grouped option writes several fields, so it overwrites anything set before it. State the ordering rule in the doc comment and keep presets first by convention.
  1. Options that read the config as well as writing it. Once an option's effect depends on what preceded it, the option list has become a program and the order stops being incidental.
  1. Exporting the function type when the set should be closed. With type Option func(*Server) exported, any package can fabricate an option that pokes at your fields. If that matters, use the interface form with an unexported apply method.
  1. Reaching for options on an internal type with two settings. Two exported functions, two doc comments and a loop, to replace a two-field struct literal. Machinery is only worth it when it buys one of the five advantages listed above.

Best Practices

  • Required arguments as parameters, optional settings as options. The signature should make it impossible to construct something meaningless.
  • Put every default in one literal at the top of the constructor, and apply options over it in order.
  • Apply first, validate second, and return an error rather than panicking - a constructor runs on the caller's input.
  • Keep the settings on an unexported config so options can never touch runtime state, and so the config's shape stays out of your API.
  • Name every option With..., give each one a single responsibility, and document in the Option type's comment that later options win.
  • Use the fallible form when values need checking, and errors.Join so one call reports every problem at once.
  • Choose the interface form, with an unexported method, when the option set must stay closed against outside implementations.
  • Prefer an exported struct when callers build configuration from files, flags or environment - and never provide both mechanisms for the same field.

Practice Exercises

  1. Add WithMaxBytes(n int) to the cache, tracking the total size of stored values and evicting when either limit is exceeded. Make its factory reject n <= 0, then call New with both WithMaxEntries(0) and WithMaxBytes(0) and confirm both messages appear in the single joined error.
  1. Convert the cache's Option from func(*config) error to the interface form with an unexported apply method. Then write a second package that tries to define its own cache.Option and record the compiler error. Explain in one sentence what that error protects you from.
  1. Add an Aggressive() preset that sets a short TTL and a small capacity. Call it once before an explicit WithTTL and once after, print the resulting TTL both times, and then write the doc comment you would ship to make the rule unambiguous.
  1. Rewrite the same cache with an exported Config struct and New(cfg Config) (*Cache, error). Put the two call sites side by side, count the lines of library code each version needs, and argue which you would ship for a public module and which for a package used only inside one service.