Go 本身,定义函数时不支持默认参数,但有时候,构建对象时需要的参数较多,有些确实不需要每次都指定,这时候如果可以实现,创建对象只传递自己需要定制的参数会方便很多。
曲线救国
我们可以将该函数定义成参数数量可变函数,可变参数为函数对象,这些函数用来设定我们需要的字段的值
例子如下:
var defaultStuffClient = stuffClient{
retries: 3,
timeout: 2,
}
type StuffClientOption func(*stuffClient)
func WithRetries(r int) StuffClientOption {
return func(o *stuffClient) {
o.retries = r
}
}
func WithTimeout(t int) StuffClientOption {
return func(o *stuffClient) {
o.timeout = t
}
}
type StuffClient interface {
DoStuff() error
}
type stuffClient struct {
conn Connection
timeout int
retries int
}
type Connection struct{}
func NewStuffClient(conn Connection, opts ...StuffClientOption) StuffClient {
client := defaultStuffClient
for _, o := range opts {
o(&client)
}
client.conn = conn
return client
}
func (c stuffClient) DoStuff() error {
return nil
}