I am using options pattern to configure the behavior of function, there are two function Foo
and Bar
which one dependent on the other, the code as follow
type fooOptions struct {
fooName string
}
type FooOptions func(*fooOptions)
func WithFooName(fooName string) {
return func(options *fooOptions) {
options.fooName = fooName
}
}
func Foo(options ...FooOptions) {
opts := &fooOptions{}
for _, opt := range options {
opt(opts)
}
// do something
}
type barOptions struct {
barName string
}
type BarOptions func(*barOptions)
func WithBarName(barName string) {
return func(options *fooOptions) {
options.barName = barName
}
}
func WithBarName(barName string) {
return func(options *barOptions) {
options.barName = barName
}
}
// compile error,unable have multi options list
func Bar(boptions ...BarOptions,fOptions ...FooOptions) {
bopts := &barOptions{}
for _, opt := range boptions {
opt(bopts)
}
Foo(fOptions...)
}
I wonder how can I have multi options list for the Bar function,or any other smart way, so I can reuse the code, otherwise I have to flatten fooOptions
into barOptions
and writing the withXXX
again
Aucun commentaire:
Enregistrer un commentaire