☰ All patterns
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.
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?