
Optional Parameters Using Option Struct
·5 mins
Introduction # In last post we learned how we can use functional options to pass parameter to our functions. In this post we’ll see an alternative way to do the same thing.
I’ll take the same code from the last post to keep things simple.
Variadic Functions for Options # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 type Coffee struct { CoffeeBeans bool Sugar bool SteamedMilk bool } func New(opts ...func(Coffee) Coffee) Coffee { coffee := Coffee{CoffeeBeans: true} for _, opt := range opts { coffee = opt(coffee) } return coffee } // WithSugar adds sugar to the coffee. func WithSugar(coffee Coffee) Coffee { coffee.Sugar = true return coffee } // WithSteamedMilk adds steamed milk to the coffee. func WithSteamedMilk(coffee Coffee) Coffee { coffee.SteamedMilk = true return coffee } // Prepare makes a cup of coffee with given items. // Ignore the implementation for now. func (c Coffee) Prepare() string { v := reflect.ValueOf(c) typeOfC := v.Type() var items []string for i := 0; i < v.NumField(); i++ { if v.Field(i).Interface() == true { items = append(items, typeOfC.Field(i).Name) } } return fmt.Sprintf("Preparing coffee with %q:", items) } func main() { s := New(WithSugar) fmt.Println(s.Prepare()) } Here on line 1-5 we define type Coffee (or class if you would like to say). This is the analogy our code is build upon because I like coffee whenever I can.
