功能选项
功能选项是一种模式,声明一个不透明 Option 类型,该类型记录某些内部结构体的信息。您的函数接受这些不定数量的选项参数,并将选项参数上的信息作用于内部结构上。
此模式可用于扩展构造函数和实现其他公共 API 中的可选参数,特别是这些参数已经有三个或者超过三个的情况下。
| Bad | Good |
|---|
// package dbfunc Connect( addr string, timeout time.Duration, caching bool,) (Connection, error) { // …}// Timeout and caching must always be provided,// even if the user wants to use the default.db.Connect(addr, db.DefaultTimeout, db.DefaultCaching)db.Connect(addr, newTimeout, db.DefaultCaching)db.Connect(addr, db.DefaultTimeout, false / caching /)db.Connect(addr, newTimeout, false / caching /)
|
type options struct { timeout time.Duration caching bool}// Option overrides behavior of Connect.type Option interface { apply(options)}type optionFunc func(options)func (f optionFunc) apply(o options) { f(o)}func WithTimeout(t time.Duration) Option { return optionFunc(func(o options) { o.timeout = t })}func WithCaching(cache bool) Option { return optionFunc(func(o options) { o.caching = cache })}// Connect creates a connection.func Connect( addr string, opts …Option,) (*Connection, error) { options := options{ timeout: defaultTimeout, caching: defaultCaching, } for _, o := range opts { o.apply(&options) } // …}// Options must be provided only if needed.db.Connect(addr)db.Connect(addr, db.WithTimeout(newTimeout))db.Connect(addr, db.WithCaching(false))db.Connect( addr, db.WithCaching(false), db.WithTimeout(newTimeout),)
|
另见,
- Self-referential functions and the design of options
- Functional options for friendly APIs