Go 本身诫舅,定義函數(shù)時(shí)不支持默認(rèn)參數(shù)笛辟,但有時(shí)候功氨,構(gòu)建對(duì)象時(shí)需要的參數(shù)較多,有些確實(shí)不需要每次都指定隘膘,這時(shí)候如果可以實(shí)現(xiàn)疑故,創(chuàng)建對(duì)象只傳遞自己需要定制的參數(shù)會(huì)方便很多。
曲線救國
我們可以將該函數(shù)定義成參數(shù)數(shù)量可變函數(shù)弯菊,可變參數(shù)為函數(shù)對(duì)象纵势,這些函數(shù)用來設(shè)定我們需要的字段的值
例子如下:
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
}