Options Pattern

A more verbose and organized way to initialize structs

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