type Options struct {
FieldA string
FieldB string
FieldC string
}
func defaultOptions() *Options {
return &Options{}
}
type Option func(*Options)
func WithA(a string) Option {
return func(o *Options) {
o.FieldA = a
}
}
func WithB(b string) Option {
return func(o *Options) {
o.FieldB = b
}
}
func WithC(c string) Option {
return func(o *Options) {
o.FieldC = c
}
}
package main
import "fmt"
func main() {
doSomething()
doSomething(WithA("this is the filed a"))
doSomething(WithA("this is the filed a"), WithB("this is the filed b"))
doSomething(WithA("this is the filed a"), WithB("this is the filed b"), WithC("this is the filed c"))
}
func doSomething(opts ...Option) {
o := defaultOptions()
for _, opt := range opts {
opt(o)
}
fmt.Printf("%+v\n", o)
}
o