Go的运行时库文档过时了吗?

huangapple go评论68阅读模式
英文:

Go's runtime library document out of date?

问题

所以,我正在使用GO解析一个POST请求。我想要的是POST请求的主体,所以我尝试了以下代码(在这个上下文中,r的类型是*http.Request):

var body io.Reader
var d []byte
body = r.Body.Reader
body.Read(d)

然而,这导致了一个编译错误:

编译错误:<文件>:44:
    r.Body.Reader未定义(类型io.ReadCloser没有字段或方法Reader)

奇怪。我本来以为它在文档中有定义...啊!在这里找到了。

现在,我对Go还比较新,但这听起来有点奇怪——我搞错了什么?

英文:

So, I'm working on parsing a POST using GO. What I want is the body of the post, so I try the following (r is of type *http.Request in this context):

var body io.Reader
var d []byte
body = r.Body.Reader
body.Read( d)

However, this results in a compilation error:

Compile error: &lt;file&gt;:44: 
    r.Body.Reader undefined (type io.ReadCloser has no field or method Reader)

Odd. I could have sworn that it was defined in the docs... Ah! here it is.

Now, I'm fairly new to Go, but this smells a little odd -- what have I screwed up?

答案1

得分: 6

从您的链接中,ReadCloser 的文档如下:

type ReadCloser interface {
    Reader
    Closer
}

这告诉您的是,ReadCloser 接口由 ReaderCloser 功能组成。它同时具备这两个功能。这意味着 ReadCloser 采用了这些接口定义。您并不是直接访问它们,它们不是实际的成员。

Reader 是:

type Reader interface {
    Read(p []byte) (n int, err error)
}

所以这意味着您应该像这样访问 Read

body = r.Body
body.Read(d)
英文:

From your link, the doc for a ReadCloser is:

type ReadCloser interface {
    Reader
    Closer
}

What this is telling you, is that a ReadCloser interface is composed of a Reader and a Closer functionality. It IS both. That means the ReadCloser takes on those interface definitions. They are not actually members, the way you are accessing them.

A Reader is:

type Reader interface {
    Read(p []byte) (n int, err error)
}

So that means you should be accessing Read like this:

body = r.Body
body.Read(d)

答案2

得分: 0

在Go文档中定义接口的方式看起来像是一个“有一个”关系。实际上,它是一个“是一个”关系,所以以下代码实现了我想要的功能:

var d []byte
r.Body.Read(d)
英文:

The way interfaces are defined in Go documents, it looked like it was a "has-a" relationship. It's actually an "is-a" relationship, so the following code does what I want:

var d []byte
r.Body.Read(d)

huangapple
  • 本文由 发表于 2012年9月8日 03:36:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/12324329.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定