Golang动态可变函数参数 参数默认值

作者:matrix 发布时间:2024-08-17 分类:Golang

Golang是不支持函数参数默认值的,但是也有很多办法可以解决

动态可变参数

func main() {
    addItem("11", "a1")
    addItem("2", "a2", "222")
}

func addItem(name, value string, opts ...string) {
    fmt.Println("add item-->", name, value)
    for _, opt := range opts {
        fmt.Println("opt:", opt)
    }
}

其中opts ...string 表示可变参数,类型为string,如果需要不同类型传入 看下面

可变参数 + 动态类型

type AlfredItem struct {
    Title    string
    Subtitle string
    Arg      int
}

type AlfredWorkflow struct {
    Items []AlfredItem
}

func (aw *AlfredWorkflow) AddItem(name, value string, opts ...func(*AlfredItem)) {
    item := AlfredItem{
        Title:    value,
        Subtitle: name,
        Arg:      111,
    }
    for _, opt := range opts {
        opt(&item)
    }
    aw.Items = append(aw.Items, item)
}

func main() {
    aw := AlfredWorkflow{}
    aw.AddItem("A", "a")
    aw.AddItem("B", "b", func(ai *AlfredItem) {
        ai.Arg = 22222
    }, func(ai *AlfredItem) {
        ai.Arg = 3333
    })

    fmt.Printf("%+v", aw)
}

高阶用法 封装为选项模式(Option Pattern)

采用Functional Options Patter方法来解决

核心点:定义 type func(*AlfredItem),且每个参数定义with函数

type AlfredItem struct {
    Title    string
    Subtitle string
    Arg      int
}

type AlfredWorkflow struct {
    Items []AlfredItem
}

type Option func(*AlfredItem)

func WithTitle(title string) Option {
    return func(ai *AlfredItem) {
        ai.Title = title
    }
}
func WithSubtitle(subtitle string) Option {
    return func(ai *AlfredItem) {
        ai.Subtitle = subtitle
    }
}

func WithArg(arg int) Option {
    return func(ai *AlfredItem) {
        ai.Arg = arg
    }
}

func (aw *AlfredWorkflow) AddItem(name, value string, opts ...Option) {
    item := AlfredItem{
        Title:    value,
        Subtitle: name,
        Arg:      111,
    }
    for _, opt := range opts {
        opt(&item)
    }
    aw.Items = append(aw.Items, item)
}

func main() {
    aw := AlfredWorkflow{}
    aw.AddItem("DefaultName", "DefaultVlaue")
    aw.AddItem("DefaultName-B", "DefaultVlaue-b", WithArg(222), WithSubtitle("0000"))
    aw.AddItem("C", "c", WithTitle("hahah"))

    fmt.Printf("%+v", aw)
}

参考:

https://www.cnblogs.com/smartrui/p/10324320.html