logo

Lucas Katayama/Options Pattern

Created Sun, 05 Apr 2020 13:52:19 -0300 Modified Sun, 05 Apr 2020 13:52:19 -0300

This is a really interesting pattern to initialize and configure a struct.

Given an app configuration

type App struct {
    name string
    port int
    addr string
}

We can have:

package main

import "fmt"

type App struct {
	name string
	port int
	addr string
}

type Option func(*App)

func New(opts ...Option) *App {
	app := &App{
		name: "Default Name",
		port: 5000,
		addr: "localhost",
	}

	for _, opt := range opts {
		opt(app)
	}
	return app
}

func WithPort(port int) func(*App) {
	return func(app *App) {
		app.port = port
	}
}

func WithName(name string) func(*App) {
	return func(app *App) {
		app.name = name
	}
}

func WithAddr(addr string) func(*App) {
	return func(app *App) {
		app.addr = addr
	}
}

func main() {
	app := New(
		WithName("Another name"),
		WithPort(8080),
		WithAddr("0.0.0.0"),
	)

	fmt.Println(app)
}

Can be tested here https://play.golang.org/p/ljnx3KQ0tVk