用with的方式实现可变参

先上代码:

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
}

 

posted @ 2023-02-28 11:08  给香菜送点香菜  阅读(30)  评论(0)    收藏  举报