如果一个办法中须要传递多个参数且某些参数又是非必传,应该如何解决?

案例

// NewFriend 寻找气味相投敌人func NewFriend(sex int, age int, hobby string) (string, error) {        // 逻辑解决 ...    return "", nil}

NewFriend(),办法中参数 sexage 为非必传参数,这时办法如何怎么写?

传参应用不定参数!

想一想怎么去实现它?

看一下这样写能够吗?

// Sex 性别type Sex int// Age 年龄type Age int// NewFriend 寻找气味相投的敌人func NewFriend(hobby string, args ...interface{}) (string, error) {    for _, arg := range args {        switch arg.(type) {        case Sex:            fmt.Println(arg, "is sex")        case Age:            fmt.Println(arg, "is age")        default:            fmt.Println("未知的类型")        }    }    return "", nil}

有没有更好的计划呢?

传递构造体... 恩,这也是一个方法。

咱们看看他人的开源代码怎么写的呢,我学习的是 grpc.Dial(target string, opts …DialOption) 办法,它都是通过 WithXX 办法进行传递的参数,例如:

conn, err := grpc.Dial("127.0.0.1:8000",    grpc.WithChainStreamInterceptor(),    grpc.WithInsecure(),    grpc.WithBlock(),    grpc.WithDisableRetry(),)

比着葫芦画瓢,我实现的是这样的,大家能够看看:

// Option custom setup configtype 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")    return "", nil}// WithSex sex 1=female 2=malefunc WithSex(sex int) Option {    return func(opt *option) {        opt.sex = sex    }}// WithAge agefunc WithAge(age int) Option {    return func(opt *option) {        opt.age = age    }}

应用的时候这样调用:

friends, err := friend.NewFriend(    "看书",    friend.WithAge(30),    friend.WithSex(1),)if err != nil {    fmt.Println(friends)}

这样写如果新增其余参数,是不是也很好配置呀。

以上。

对以上有疑难,快来我的星球交换吧 ~ https://t.zsxq.com/iIUVVnA