函数选项模式

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

// CustomStruct your defined struct
type CustomStruct struct {
a string
b string
}

// func function type
type OptionFunc func(*CustomStruct)

// edit the value of a
func InsertA(a string) OptionFunc {
return func(o *CustomStruct) {
o.a = a
}
}

// edit the value of b
func InsertB(b string) OptionFunc {
if b == "" {
b = "Default value B"
}
return func(o *CustomStruct) {
o.b = b
}
}

// return object
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)
}