Skip to content
GDP for Noobs
☰ All patterns
CreationalIntermediate

Functional Options

Go's favourite way to make constructors with optional settings.

01

Explain it like I'm new

Real-life analogy

Customising a coffee order

A latte comes with sensible defaults. You can say 'oat milk' or 'extra shot', in any order, or nothing at all. Each request is a small tweak on top of the default.

😩 The problem

Go has no default parameters or overloading. NewServer(host, port, timeout, maxConns, tls, ...) breaks every caller each time you add an option.

💡 The pattern

Make Option a function type that modifies the struct. The constructor sets defaults, then applies each option passed via a variadic parameter.

02

Walk through the code

Click a step to highlight its lines. This is a complete program you can copy and run.

main.go
1package main
2
3import (
4 "fmt"
5 "time"
6)
7
8type Server struct {
9 host string
10 port int
11 timeout time.Duration
12 maxConns int
13}
14
15// Option is just a function that tweaks a *Server.
16type Option func(*Server)
17
18// Each WithXxx returns an Option that sets one field.
19func WithPort(p int) Option {
20 return func(s *Server) { s.port = p }
21}
22
23func WithTimeout(d time.Duration) Option {
24 return func(s *Server) { s.timeout = d }
25}
26
27func WithMaxConns(n int) Option {
28 return func(s *Server) { s.maxConns = n }
29}
30
31// NewServer sets defaults first, then applies any options the caller passed.
32func NewServer(host string, opts ...Option) *Server {
33 s := &Server{host: host, port: 8080, timeout: 30 * time.Second, maxConns: 100}
34 for _, opt := range opts {
35 opt(s)
36 }
37 return s
38}
39
40func (s *Server) String() string {
41 return fmt.Sprintf("%s:%d (timeout=%s, maxConns=%d)", s.host, s.port, s.timeout, s.maxConns)
42}
43
44func main() {
45 // Zero options: all defaults. Readable and short.
46 fmt.Println("dev: ", NewServer("localhost"))
47
48 // Only override what you care about, in any order.
49 prod := NewServer("api.example.com",
50 WithPort(443),
51 WithTimeout(5*time.Second),
52 WithMaxConns(10_000),
53 )
54 fmt.Println("prod:", prod)
55}
terminal
Press ▶ Run to execute this program.

This output was captured by running the program with Go 1.24. Copy it into your editor or the Go Playground and try changing things.

03

When should I use it?

✅ Reach for it when…

  • •Public library constructors with several optional settings.
  • •APIs that need to grow without breaking existing callers.

🚫 Skip it when…

  • •Settings are all required. Just use normal parameters.
  • •A simple Config struct would be clearer.

🐹 Go tip

If an option can fail validation, use type Option func(*Server) error and return the error from the constructor.

🌍 You've already seen it in

grpc.Dial(addr, grpc.WithTransportCredentials(...)), zap.New(core, zap.AddCaller()) and many cloud SDKs.

04

Quick check

One question. No pressure.

What is `Option` in this pattern?

Related: Builder, Singleton