0PricingLogin
Go Academy · Lesson

Option Functions

Configure with functions.

Configure with Functions

The core idea: represent each optional setting as a function that mutates a config. These are the "option functions".

The Option Type

Define an Option as a function taking a pointer to the config struct.

package main

import "fmt"

type Config struct {
	Port    int
	Timeout int
}

type Option func(*Config)

func main() {
	var o Option
	fmt.Println(o == nil)
}

All lessons in this course

  1. The Problem with Many Params
  2. Option Functions
  3. Building a Flexible API
  4. Defaults and Validation
← Back to Go Academy