Level: IntermediateGo Lang

Go Functional Options Pattern Explained Simply

8 min read
Go Functional Options featured image: WithPort, WithTLS and default timeout cards

Go functional options are a clean way to build objects that have many settings. In this post, you will learn why long constructors become painful and how options fix that. Then we will build a small server type with safe defaults and optional settings.

This lesson builds on Go functions and Go closures. We also use ideas from Go structs and Go error wrapping. So it helps to read those first.

What Are Go Functional Options?

Suppose you write a NewServer function. At first, it takes one argument, which is the address. Then someone wants a port, so you add a second argument. Next comes a timeout, then a TLS flag, then a logger. Soon, the call looks like NewServer("localhost", 8080, 30, true, nil), and nobody knows what each value means.

Go functional options solve this problem. Instead of many arguments, the constructor takes the one required value plus any number of small option functions. Each option changes one setting, so you pass only the options you care about.

Think of ordering a coffee. You say “a large latte” and then you add “with oat milk” and “extra hot”. You do not fill in a form with twenty boxes. In the same way, Go functional options let you name just the changes you want, and nothing else.

Why Go Functional Options Matter

Go has no default arguments and no function overloading. Because of that, a constructor with many settings is hard to design. Here is what Go functional options give you.

  • Readable calls: each option has a name, such as WithPort(443).
  • Safe defaults: the constructor fills in good values when you pass nothing.
  • Easy growth: you can add a new option later without breaking old callers.
  • Clean code: no struct full of zero values that may or may not be set on purpose.

However, options add a small amount of code. For a type with only two settings, a plain struct is often simpler. So use Go functional options when a type has several optional settings or when you expect it to grow.

How Go Functional Options Work

The idea has three parts. First, an Option is a function type that receives a pointer to the object. Second, each WithSomething helper returns an option that changes one field. Third, the constructor builds the object with defaults and then runs every option on it.

Go Functional Options diagram showing NewServer applying defaults and then the WithPort and WithTLS options
NewServer creates a server with defaults, then runs each option in order. WithPort, WithTLS and WithTimeout each change one field and return control to the constructor.

Why a Function Type Works So Well

In Go, functions are values. A closure can remember a variable from the place where it was created. When you call WithPort(443), the returned function remembers the number 443. Later, the constructor runs that function. As a result, the port is set. If you want a refresher, our Go closures post explains this idea in detail.

Why the Order of Options Matters

Options run in the order you pass them, and this order is easy to see. So when two options change the same field, the last one wins. This is usually what people expect. Still, you should document it. This matters most when options depend on each other.

Go Functional Options vs Other Approaches

There are a few ways to configure an object in Go. The table below compares them.

ApproachExampleStrengthWeakness
Long argument listNewServer(addr, 8080, 30, true)Simple for two valuesHard to read, hard to extend
Config structNewServer(Config{Port: 8080})Easy to readZero values hide intent
Builder methodsNewServer().Port(8080).TLS()Fluent styleMore code and mutable state
Functional optionsNewServer(addr, WithPort(8080))Clear, safe defaultsSlightly more code
Go Functional Options diagram comparing a config struct with functional options
A config struct needs every field to be filled or left as zero. Functional options start from defaults and apply only the changes the caller names.

So a config struct is a fine choice for small types. Functional options shine when defaults matter and the API must stay stable over years. Many well known Go libraries use Go functional options for this reason.

Go Functional Options Hands-On: A Server Type

Now let’s write the code. We keep the server tiny so the pattern stays in focus.

Step 1: The Type and the Options

First, the Server struct has four fields. Next, Option is a function that takes *Server. Then each helper returns a closure that sets one field.

type Server struct {
	addr    string
	port    int
	timeout time.Duration
	tls     bool
}

type Option func(*Server)

func WithPort(p int) Option               { return func(s *Server) { s.port = p } }
func WithTimeout(d time.Duration) Option { return func(s *Server) { s.timeout = d } }
func WithTLS() Option                     { return func(s *Server) { s.tls = true } }

Step 2: The Constructor

Then the constructor takes the address and a variadic list of options. The three dots mean that the caller may pass zero or more of them. It sets safe defaults first and runs each option after that.

func NewServer(addr string, opts ...Option) *Server {
	s := &Server{addr: addr, port: 8080, timeout: 30 * time.Second}
	for _, opt := range opts {
		opt(s)
	}
	return s
}

Let’s look at the key lines. The defaults live in one place, so every caller gets the same safe start. Also, a later change to a default happens in a single line. Then the loop runs each option in the given order. Finally, the return type is a pointer, so the caller shares the same object that the options changed.

Step 3: Use It

Finally, we build two servers. The first uses only defaults. The second changes the port, turns on TLS and sets a short timeout.

func main() {
	a := NewServer("localhost")
	b := NewServer("api.example.com", WithPort(443), WithTLS(), WithTimeout(5*time.Second))
	for _, s := range []*Server{a, b} {
		fmt.Printf("%s:%d timeout=%v tls=%v\n", s.addr, s.port, s.timeout, s.tls)
	}
}

Here is the real output from our run.

localhost:8080 timeout=30s tls=false
api.example.com:443 timeout=5s tls=true

As you can see, the first server keeps every default, because we passed no options. The second server changes exactly the three settings we named. The call reads almost like a sentence, and that is the main gain of Go functional options. In addition, new options never break old calls.

Where You Will See Go Functional Options

You will meet this pattern in many real projects. Popular libraries use it for clients, servers and loggers. The table below lists a few typical settings and the matching option names.

SettingDefaultOption name
Port8080WithPort(443)
Timeout30 secondsWithTimeout(5 * time.Second)
Secure modeOffWithTLS()
Retry count3WithRetries(5)
LoggerStandard loggerWithLogger(l)

When you read a library that follows this style, look for the With helpers first. They show every setting at a glance. Also, check the constructor for the default values, because they tell you what happens when you pass nothing.

How to Test Options

Options are easy to test. Build an object with one option, then check the field. For instance, create a server with WithPort(443) and confirm that the port is 443. Likewise, create one with no options and check the defaults. Because each option does one thing, each test stays short.

Options That Can Fail

Sometimes an option gets a bad value, such as port 70000. In that case, let the option return an error. Then the constructor stops at the first error, because a half-built object is not useful. It also wraps the error. The result of a second small program looks like this.

type Option func(*Server) error

func WithPort(p int) Option {
	return func(s *Server) error {
		if p < 1 || p > 65535 {
			return errors.New("port must be between 1 and 65535")
		}
		s.port = p
		return nil
	}
}

func NewServer(addr string, opts ...Option) (*Server, error) {
	s := &Server{addr: addr, port: 8080}
	for _, opt := range opts {
		if err := opt(s); err != nil {
			return nil, fmt.Errorf("new server: %w", err)
		}
	}
	return s, nil
}

We call it with a good port and then with a bad one. Here is the real output.

localhost 9090 <nil>
true new server: port must be between 1 and 65535

In the first case, the call returns a server and no error. In the second case, it returns a nil server and a clear message. Because of %w, the caller can still check the cause with errors.Is.

Common Mistakes with Go Functional Options

  • Using options for one required value: the address is required, so it stays a normal argument. Options are only for optional settings.
  • Hidden side effects: an option should only change the object. So avoid network calls or file reads inside it, because they make tests slow.
  • Missing defaults: without defaults, a caller who passes nothing gets a broken object. Therefore, set safe values first, before any option runs.
  • Exporting the fields: if fields are public, callers can skip the options. Instead, keep fields private.
  • Forgetting the order rule: the last option wins. So document any pair of options that conflict.

Best Practices for Go Functional Options

  • Name helpers with a With prefix, because the call then reads like English.
  • Keep one option for one setting, since small pieces are easy to test.
  • Set defaults in the constructor, which gives every caller the same safe start.
  • Return an error from options that can fail, so bad input never creates a half-built object.
  • Use a variadic parameter, because callers can pass zero options and still compile.
  • Keep the option type exported, so users can build their own lists and reuse them.

Practice Task

To practise Go functional options, add WithLogger(l *log.Logger) and WithMaxConns(n int) to the server. Then print both values from main.

Hint: add two fields to the struct and set a default for each. After that, make WithMaxConns reject numbers below one, as the error version did for ports.

Official Resources

These pages describe the language features and ideas used in this lesson.

Quick Recap

  • Go functional options configure an object with named, optional settings.
  • An option is a function type that changes one field through a pointer.
  • The constructor sets safe defaults and then runs each option in order.
  • Options can return errors, so bad values stop construction.
  • Use a config struct for small types and options for growing APIs.
  • Keep fields private so callers must use the options.

What’s Next?

By now, you can design a constructor that stays clean as it grows. However, we have used methods and receivers in many examples without a full look. So next, we will compare value and pointer receivers in detail.

Next up: Go methods with value and pointer receivers