小编典典

转到构造函数类型

go

我想知道是否有人可以向我解释这种语法:

// Client may be used to make requests to the Google Maps WebService APIs
type Client struct {
    httpClient        *http.Client
    apiKey            string
    baseURL           string
    clientID          string
    signature         []byte
    requestsPerSecond int
    rateLimiter       chan int
}

// ClientOption is the type of constructor options for NewClient(...).
type ClientOption func(*Client) error

var defaultRequestsPerSecond = 10

// NewClient constructs a new Client which can make requests to the Google Maps WebService APIs.
func NewClient(options ...ClientOption) (*Client, error) {
    c := &Client{requestsPerSecond: defaultRequestsPerSecond}
    WithHTTPClient(&http.Client{})(c)
    for _, option := range options {
        err := option(c)
        if err != nil {
            return nil, err
        }
    }
    .....

我不了解ClientOption发生了什么。指向客户端的函数类型会返回错误吗?然后在NewClient中,它看起来像接受了ClientOption类型的数组并返回了指向Client的新指针。我不确定这是否正确,是否有人可以解释得更多,或者给我一个类似于许多Javascript库所做的类比的不确定性,

options: {
    property1: "someproperty",
    property2: "anotherproperty"
}

在构造函数中。


阅读 241

收藏
2020-07-02

共1个答案

小编典典

ClientOption是一个接受客户端指针并返回错误(可能为nil)的函数。

例如,下面是创建ClientOption函数的超时函数:

func WithTimeout(duration time.Duration) ClientOption {
    return func(c *Client) error {
        c.timeout = duration
        return nil
    }
}

NewClient函数接受可变数量的ClientOption参数,可在“选项”切片中使用。它创建一个新的客户端,通过将客户端指针传递给每个ClientOption对其进行配置,然后返回该指针。

它可以如下使用:

client := NewClient(WithTimeout(3 * time.Second))

请参阅Rob Pike的自引用函数和Dave
Cheney的选项文章

2020-07-02