-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Guideline: For functional options, don't recommend closures #74
Copy link
Copy link
Closed
Description
Our recommendation right now includes this pattern,
type Option interface{ apply(*options) }
type optionFunc func(*options)
And then all options are implemented using optionFunc and closures.
func WithTimeout(d time.Duration) Option {
return optionFunc(func(o *options) {
o.Timeout = d
})
}
This is not the pattern we should be encouraging because it makes Options
too opaque. We cannot print them or compare them, or introspect values inside
them.
We should instead recommend declaring a new type for each option.
type timeoutOption time.Duration
func WithTimeout(t time.Duration) Option {
return timeoutOption(t)
}
func (o timeoutOption) apply(opts *options) {
opts.Timeout = time.Duration(o)
}
// And
type loggerOption struct{ L *zap.Logger }
func WithLogger(l *zap.Logger) Option {
return loggerOption{L: l}
}
func (o *loggerOption) apply(opts *options) {
o.Logger = o.L
}
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels