type Options struct {
StrOption1 string
StrOption2 string
StrOption3 string
IntOption1 int
IntOption2 int
IntOption3 int
}
type Option func(opts *Options)
func InitOption3(opts ...Option) { options := &Options{} for _, opt := range opts { opt(options) } fmt.Printf("init options3:%#v\n", options) }
func WithStringOption1(str string) Option { return func(opts *Options) { opts.StrOption1 = str } } func WithStringOption2(str string) Option { return func(opts *Options) { opts.StrOption2 = str } } func WithStringOption3(str string) Option { return func(opts *Options) { opts.StrOption3 = str } } func WithIntOption1(val int) Option { return func(opts *Options) { opts.IntOption1 = val } } func WithIntOption2(val int) Option { return func(opts *Options) { opts.IntOption2 = val } } func WithIntOption3(val int) Option { return func(opts *Options) { opts.IntOption3 = val } }
func main() { InitOption3( WithStringOption1("str1"), WithStringOption3("str3"), WithIntOption3(3), WithIntOption2(2), WithIntOption1(1), WithStringOption2("str2"), ) }
执行:
init options3:&main.Options{StrOption1:"str1", StrOption2:"str2", StrOption3:"str3", IntOption1:1, IntOption2:2, IntOption3:3}
本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/p/13574121.html