用户工具

站点工具


golang:index:optionalfunction

Optional Function

//example
 
type Foo struct {
    Num int
    Str string
}
 
type Option func(f *Foo)
 
func WithNum(num int) Option {
  return func(f *Foo) {
    f.Num = num
  }
}
 
func WithStr(str string) Option {
  return func(f *Foo) {
    f.Str = str
  }
}
 
func New(someRequiredField string, opts ...Option) *Foo {
  foo := &Foo{
    Num: 10,
    Str: "hello",
  }
 
  for _, applyOpt := range opts {
    applyOpt(foo)
  }
 
  return &foo
}
 
func main() {
  foo := New("important", WithNum(30))
  foo = New("required", WithNum(20), WithStr("hello"))
}
golang/index/optionalfunction.txt · 最后更改: 2021/10/20 12:00 由 admin