go - 看懂这段代码(golang),双括号()()

标签 go

我想知道是否有人可以向我解释这种语法。在 google maps go 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,但随后它还传入了指向在其上方声明的客户端结构的指针?

最佳答案

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)

关于go - 看懂这段代码(golang),双括号()(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41727326/

相关文章:

go - 如何持续分析我的 go 应用程序?

json - 根据类型解码时为空字段

ssl - Golang ListenAndServeTLS 不会接受我的证书

apache - 使用 Apache 部署 Go Web 应用程序

go - 在几个不同的 goroutine 之间共享一个 slice

json - 在 GO 中发送 POST 请求时收到错误响应 - 来自服务器的 422

go - 我可以在main中定义一个接收方法吗?

go - 通过 SetDeadline() 为 TCP 监听器设置超时

go - 在Golang(yaml)中将特定结构解码为字符串

go - 一个 Go 程序默认启动了多少个 goroutine?