body.Read 未定义(类型 *io.ReadCloser 没有字段或方法 Read)

Fil*_*und 0 go

我似乎无法解决这个奇怪的错误。这是我的代码:

resp, err := http.Get("example.com/my/text/file.conf")
...
err = parseEvent(eventchan, &resp.Body)

func parseEvent(eventchan chan Event, body *io.ReadCloser) error {
raw := make([]byte, 1024*1024*32, 1024*1024*32)
n, err := body.Read(raw)
Run Code Online (Sandbox Code Playgroud)

我得到这个奇怪的错误:

./igen.go:91: body.Read 未定义(类型 *io.ReadCloser 没有字段或方法读取)

第 91 行是n, err := body.Read(raw)上面的行。

我错过了什么?Golang.org 告诉我 ReadCloser 实现了 Reader,它具有Read(p []byte) (n int, err error)我试图调用的方法。

Not*_*fer 6

您的参数是body *io.ReadCloser- 表示指向接口的指针ReadCloser,界面,有Read()。只需将您的函数签名更改为:

func parseEvent(eventchan chan Event, body io.ReadCloser) error
Run Code Online (Sandbox Code Playgroud)

  • @FilipHaglund(抱歉耽搁了)。如果结构实现了接口,则指向该结构的指针仍然实现该接口。所以你可以将指针作为接口的值传递。一开始有点令人困惑,但是一旦你掌握了它,它就是 Go 中最棒的原则之一。 (2认同)