Created
May 23, 2022 21:03
-
-
Save piotrpersona/8ac3ce6c0bec14aa2074b4fb7b6c9d20 to your computer and use it in GitHub Desktop.
Options pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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