pointers - 如何使用指针

标签 pointers go

假设我有这个功能

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 ...
}

Source code

从上面的定义可以看出,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/

相关文章:

c - C 中的链表中的链表,读取第二个列表时出现段错误

c++ - syslog const char* 到字符串

go - golang 中的中间件

c++ - C中的动态大小数组

c - 在连接到服务器之前尝试编译客户端时出错

json - 向不同系统发送 MongoDB 查询 : converting to JSON and then decoding into BSON? Go 语言如何实现?

go - Go 中并发例程的打印问题

go - 解码 json 字段是 int 或 string

c - 为什么这是按值(value)传递?

go - 字符串到日期的转换(带有 +0530 的 IST)