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
| package main
type CustomStruct struct { a string b string }
type OptionFunc func(*CustomStruct)
func InsertA(a string) OptionFunc { return func(o *CustomStruct) { o.a = a } }
func InsertB(b string) OptionFunc { if b == "" { b = "Default value B" } return func(o *CustomStruct) { o.b = b } }
func NewObject(opts ...OptionFunc) *CustomStruct { o := &CustomStruct{} for _, opt := range opts { opt(o) } return o }
func main() { myObject := NewObject(InsertA("Inserted value"), InsertB("")) println(myObject.b) }
|