【问题标题】:body.Read undefined (type *io.ReadCloser has no field or method Read)body.Read 未定义(类型 *io.ReadCloser 没有读取字段或方法)
【发布时间】:2014-10-16 21:10:26
【问题描述】:

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

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)

我得到了这个奇怪的错误:

./igen.go:91: body.Read undefined(类型*io.ReadCloser没有Read字段或方法)

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

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

【问题讨论】:

  • 仔细查看错误信息:*io.ReadCloser,而不是io.ReadCloser。函数 parseEvent 不应使用指向接口的指针。

标签: go


【解决方案1】:

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

func parseEvent(eventchan chan Event, body io.ReadCloser) error

【讨论】:

  • 这不是按值传递,而不是按引用传递吗?
  • 等等,我是否通过值传递接口,而不是实现该接口的结构实例?
  • @FilipHaglund(抱歉耽搁了)。如果结构实现了接口,则指向该结构的指针仍实现该接口。因此您可以将指针作为接口的值传递。一开始有点困惑,但一旦你掌握了它,它就是围棋最棒的原理之一。
猜你喜欢
  • 2017-08-03
  • 1970-01-01
  • 1970-01-01
  • 2021-02-22
  • 1970-01-01
  • 2020-12-24
  • 1970-01-01
  • 2021-11-26
  • 2021-08-02
相关资源
最近更新 更多