假设我有这个功能
func main() {
x := 10
change(&x)
}
func change(n *int) {
}
如果我不在 n *int
中使用签名,上面的函数会报错 -
*cannot use &x (type int) as type int in argument to change
但是为什么下面的示例运行良好而不需要在发送方法的参数中使用客户端 *HTTPClient 尽管我在这种情况下传递了一个指针?
import (
"net/http"
)
// HTTPClient interface for making http requests
type HTTPClient interface {
Get(url string) (*http.Response, error)
}
func main() {
client := &http.Client{}
err := send(client, url)
}
func send(client HTTPClient, url string) error {
}
最佳答案
HTTPClient
是一个接口(interface),它定义了一个方法 Get(...)
来自 http.Client
的客户端结构也有一个 get 方法,docs here.
func (c *Client) Get(url string) (resp *Response, err error) {
// trimmed ...
}
从上面的定义可以看出,Get(url)
有一个“指针接收者”。这意味着 *http.Client
定义了 Get(url)
方法并且没有 http.Client
。这意味着 *httpClient
实现了 HTTPClient
接口(interface),而不是 http.Client
。
最后值得指出的是,如果 an 接口(interface)是由“值接收者”而不是“指针接收者”实现的,go 运行时将自动取消引用指针。
这方面的一个例子可能是:
type Valuer interface {
Value() string
}
type V struct {}
type (valueReceiver V) Value() string {
// trimmed ...
}
// Here given a *V not V, go will dereference *V to call the Value() method on V not *V
vPtr := &V{}
vPtr.Value()
关于pointers - 如何使用指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50898117/