package main import "fmt" const ( defaultName string = "张建平" defaultAge int = 27 defaultHigh int = 175 ) type User struct { Name string Age int High int } type UserOptions struct { Name string Age int High int } type UserOption interface { apply(*UserOptions) } type FuncUserOption struct { f func(*UserOptions) } func (fo FuncUserOption) apply(option *UserOptions) { fo.f(option) } func WithName(name string) UserOption { return FuncUserOption{ f: func(options *UserOptions) { options.Name = name }, } } func WithAge(age int) UserOption { return FuncUserOption{ f: func(options *UserOptions) { options.Age = age }, } } func WithHigh(high int) UserOption { return FuncUserOption{f: func(options *UserOptions) { options.High = high }} } func NewUser(opts ...UserOption) *User { options := UserOptions{ Name: defaultName, Age: defaultAge, High: defaultHigh, } for _, opt := range opts { opt.apply(&options) } return &User{ Name: options.Name, Age: options.Age, High: options.High, } } func main() { u1 := NewUser() fmt.Println(u1) u2 := NewUser(WithName("胖虎")) fmt.Println(u2) u3 := NewUser(WithName("喵"), WithAge(3)) fmt.Println(u3) }
标签:选项卡,Name,UserOptions,int,Age,模式,func,go,options From: https://www.cnblogs.com/52-qq/p/17515434.html