理解这段代码(golang),双重parantheses()()

时间:2017-01-18 18:58:16

标签: go

我想知道是否有人可以向我解释这种语法。在google地图中去api,他们有

type Client struct {
    httpClient        *http.Client
    apiKey            string
    baseURL           string
    clientID          string
    signature         []byte
    requestsPerSecond int
    rateLimiter       chan int
}

// 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
        }
    }
    if c.apiKey == "" && (c.clientID == "" || len(c.signature) == 0) {
        return nil, errors.New("maps: API Key or Maps for Work credentials missing")
    }

    // Implement a bursty rate limiter.
    // Allow up to 1 second worth of requests to be made at once.
    c.rateLimiter = make(chan int, c.requestsPerSecond)
    // Prefill rateLimiter with 1 seconds worth of requests.
    for i := 0; i < c.requestsPerSecond; i++ {
        c.rateLimiter <- 1
    }
    go func() {
        // Wait a second for pre-filled quota to drain
        time.Sleep(time.Second)
        // Then, refill rateLimiter continuously
        for _ = range time.Tick(time.Second / time.Duration(c.requestsPerSecond)) {
            c.rateLimiter <- 1
        }
    }()

    return c, nil
}

// WithHTTPClient configures a Maps API client with a http.Client to make requests over.
func WithHTTPClient(c *http.Client) ClientOption {
    return func(client *Client) error {
        if _, ok := c.Transport.(*transport); !ok {
            t := c.Transport
            if t != nil {
                c.Transport = &transport{Base: t}
            } else {
                c.Transport = &transport{Base: http.DefaultTransport}
            }
        }
        client.httpClient = c
        return nil
    }
}

这是我在NewClient中无法理解的一句话

WithHTTPClient(&http.Client{})(c)

为什么有两个()()? 我看到WithHTTPClient接受了该行所做的* http.Client,但是它还传入一个指向它上面声明的客户端结构的指针?

1 个答案:

答案 0 :(得分:6)

WithHTTPClient返回一个函数,即:

func WithHTTPClient(c *http.Client) ClientOption {
    return func(client *Client) error {
        ....
        return nil
    }
}

WithHTTPClient(&http.Client{})(c)只是将c(指向客户端的指针)作为参数调用该函数。它可以写成:

f := WithHTTPClient(&http.Client{})
f(c)