NOTE

Functional Options Pattern

A Go functional-options example for constructing an object with default values while allowing selected fields to be changed flexibly.

Software Architecture & EngineeringCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Definition

  • Create an object with default values while allowing its properties to be modified flexibly.
    • We may need to specify default values for fields in Option.
    • The fields in Option may change over time.

2. Golang

2.1. Object to Be Created

package 函数式选项模式

var defaultOption = &Option{
	Name: "[REDACTED]",
	Age:  25,
	Sex:  true,
}

// Function type used to modify struct fields
type OptionFunc func(option *Option)

// A regular struct
type Option struct {
	Name string
	Age  int
	Sex  bool
}

// Define a method for each field of the struct
func WithName(name string) OptionFunc {
	return func(option *Option) {
		option.Name = name
	}
}

func WithAge(age int) OptionFunc {
	return func(option *Option) {
		option.Age = age
	}
}

func WithSex(sex bool) OptionFunc {
	return func(option *Option) {
		option.Sex = sex
	}
}

// Constructor
func NewOption(opts ...OptionFunc) *Option {
	opt := defaultOption
	for _, o := range opts {
		o(opt)
	}
	return opt
}

2.2. Test

package 函数式选项模式

import (
	"fmt"
	"testing"
)

func TestNewOption(t *testing.T) {
	opt := NewOption()
	fmt.Println("default option:", opt)
	opt2 := NewOption(WithAge(33))
	fmt.Println("modified option:", opt2)
}

// Output
default option: &{[REDACTED] 25 true}
modified option: &{[REDACTED] 33 true}

3. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub