函数式选项模式
初始化字段时设置默认值,可以使用函数式选项模式,使用方法如下:
type Option struct {
A string
B string
C int
}
//第一步
func WithA(a string) func(o *Option) {
return func(o *Option) {
o.A = a
}
}
func WithB(b string) func(o *Option) {
return func(o *Option) {
o.B = b
}
}
func WithC(c int) func(o *Option) {
return func(o *Option) {
o.C = c
}
}
//第二步
func newOption2(opts ...OptionFunc) (opt *Option) {
opt = defaultOption
for _, o := range opts {
o(opt)
}
return
}
//测试
func main() {
x := newOption("nazha", "小王子", 10)
fmt.Println(x)
x = newOption2()
fmt.Println(x)
x = newOption2(
WithA("沙河娜扎"),
WithC(250),
)
fmt.Println(x)
}

浙公网安备 33010602011771号