当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《理解这段代码(golang),双重parantheses()()》经验,为你挑选了1个好方法。

我想知道是否有人可以向我解释这种语法.在谷歌地图去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> hlscalon..:

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)

推荐阅读
有风吹过best
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有