Skip to content

函数式参数

Functional Options Pattern / 函数式选项模式

  1. 延迟配置(deferred config)
  2. 可选参数(optional params)
  3. 行为组合(composable behavior)
go

type Option func(*fields)

type fields struct {
    status string
    err    error
}


func WithStatus(status string) Option {
    return func(f *fields) {
        f.status = status
    }
}


func WithErr(err error) Option {
    return func(f *fields) {
        f.err = err
    }
}


func Log(action string, opts ...Option) {
    f := &fields{}

    for _, opt := range opts {
        opt(f) // 执行函数,修改 f
    }

    fmt.Println(f.status, f.err)
}

考虑是否使用

参数是否:

  1. 可选?
  2. 会扩展?
  3. 顺序不重要?