package main
import "fmt"
type optionClient func(*options)
func setAge(a int) optionClient {
return func(o *options) {
o.Age = a
}
}
func setSex(s int) optionClient {
return func(o *options) {
o.Sex = s
}
}
type options struct {
Age int
Sex int
}
type Settings struct {
Age int
Sex int
Name string
}
func NewSettings(Name string, clients ...optionClient) *Settings {
option := options{26, 0}
for _, f := range clients { //如果传入了自定义参数就会修改默认option,如果没有传入自定义参数,只是传入了姓名,就会用默认的option的值去设置
f(&option)
}
return &Settings{
Age: option.Age,
Sex: option.Sex,
Name: "",
}
}
func main() {
settings := NewSettings("Jerry", setAge(100), setSex(0))
fmt.Print(settings.Age)
}