gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 02:26:26 26 4
gpt4 key购买 nike

我想知道是否有人可以向我解释这种语法。在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com