先上代码:
package main import "fmt" // Option custom setup config type Option func(*option) // option 参数配置项 type option struct { sex int age int } // NewFriend 寻找志同道合的朋友 func NewFriend(hobby string, opts ...Option) (string, error) { opt := new(option) for _, f := range opts { f(opt) } fmt.Println(opt.sex, "is sex") fmt.Println(opt.age, "is age") fmt.Println(hobby) return hobby, nil } // WithSex sex 1=female 2=male func WithSex(sex int) Option { return func(opt *option) { opt.sex = sex } } // WithAge age func WithAge(age int) Option { return func(opt *option) { opt.age = age } } func name() { friends, err := NewFriend("看书", WithAge(30), WithSex(1)) if err != nil { fmt.Println(err) } else { fmt.Println(friends) } }
还有2种方式
接口模式
// Sex 性别 type Sex int // Age 年龄 type Age int // NewFriend 寻找志同道合的朋友 func NewFriend(hobby string, args ...interface{}) (string, error) { return "", nil }
结构体
// option 参数配置项 type option struct { sex int age int } // NewFriend 寻找志同道合的朋友 func NewFriend(hobby string,opt option) (string, error) { return "", nil }
标签:opt,option,方式,实现,age,sex,int,func,可变 From: https://www.cnblogs.com/mingkewang/p/17163309.html