Skip to content

Instantly share code, notes, and snippets.

@piotrpersona
Created May 23, 2022 21:03
Show Gist options
  • Save piotrpersona/8ac3ce6c0bec14aa2074b4fb7b6c9d20 to your computer and use it in GitHub Desktop.
Save piotrpersona/8ac3ce6c0bec14aa2074b4fb7b6c9d20 to your computer and use it in GitHub Desktop.
Options pattern
package main
import (
"fmt"
)
type engineOption func(e *Engine)
func WithFuel(fuel float64) engineOption {
return func(e *Engine) {
e.fuel = fuel
}
}
func WithAutomatic() engineOption {
return func(e *Engine) {
e.automaticTransmission = true
}
}
type Engine struct {
fuel float64
automaticTransmission bool
}
func NewEngine(opts ...engineOption) *Engine {
e := &Engine{fuel: 0, automaticTransmission: false}
for _, opt := range opts {
opt(e)
}
return e
}
func main() {
e := NewEngine()
fmt.Printf("%+v\n", e)
e = NewEngine(WithFuel(3.20), WithAutomatic())
fmt.Printf("%+v\n", e)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment