547.

Dysfunctional options pattern in Go

rednafi.com/go/dysfunctional_options_pattern
package src

type config struct {
    // Required
    foo, bar string

    // Optional
    fizz, bazz int
}

// Each optional configuration attribute will have its own public method
func (c *config) WithFizz(fizz int) *config {
    c.fizz = fizz
    return c
}

func (c *config) WithBazz(bazz int) *config {
    c.bazz = bazz
    return c
}

// This only accepts the required options as params
func NewConfig(foo, bar string) *config {
    // First fill in the options with default values
    return &config{foo, bar, 10, 100}
}

func Do(c *config) {}

You’d use the API as follows:

package main

import ".../src"

func main() {
    // Initialize the struct with only the required options and then chain
    // the option methods to update the optional configuration attributes
    c := src.NewConfig("hello", "world").WithFizz(0).WithBazz(42)
    src.Do(c)
}