为什么当我使用一个包的方法时,它说它属于不同的类型?

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

How come I can use a packages method when it says it belongs to a different type?

问题

抱歉,标题写得很糟糕,首先,如果有人在阅读我的问题后能提供一个更好的标题,请提交,我对术语还不太熟悉。

所以,简单的问题:

我正在阅读net/http包中关于如何进行http.Get请求的内容,它说我只需要执行以下操作:

resp, err := http.Get(blah)

好的,很公平,所以我向下滚动列表,看看这个Get函数需要哪些参数,但我在http包的函数下面没有找到它。

所以我继续向下滚动,在type Client下找到了一个Get方法。

那么为什么我不需要先创建一个http.Client,然后向其发出Get请求呢?有点困惑。谢谢任何帮助。

英文:

Sorry for the horrible horrible title, first off if anybody can offer an edit for a better title after reading my question please, submit it, I'm pretty bad with my terminology at the moment.

So, simple question:

Reading through the net/http package on how to make http.Get requests and it says all I have to do is

resp, err := http.Get(blah)

Ok fair enough so scrolling down the list to see what parameters this Get function took, I couldn't find it directly under the functions of the http package

So scrolling down I find a Get method under type Client

So how come I don't have to first http.Client then make my Get request to that? Just a little confused. Thanks for any help.

答案1

得分: 3

这是两种不同版本的方法。在一种情况下,http.Get是在包级别定义的,这类似于C#或Java中的静态方法。在另一种情况下,它具有类型为http.Client的接收器,类似于C#或Java中该类型的实例方法。类型http.Client与您在同一个包中所期望的一样。

包级别的Get方法:
http://golang.org/pkg/net/http/#Get

 func Get(url string) (resp *Response, err error)
    //^ 没有接收器 = 包级别的方法
    //^ 大写的方法名,因此它是“导出的”,类似于public

带有Client接收器的Get方法:
http://golang.org/pkg/net/http/#Client.Get

   func (c *Client) Get(url string) (resp *Response, err error)
        //^ 这是接收器
英文:

Those are two different versions of the method. In one case; http.Get it's defined at the package level, this works much like a static method in C# or Java. In the other it has a receiver of type http.Client it's more like an instance method on that type in C# or Java. The type http.Client is as you'd expect in the same package.

package level get:
http://golang.org/pkg/net/http/#Get

 func Get(url string) (resp *Response, err error)
    //^ absence of receiver = package scoped
    //^ uppercase method name so it is 'exported' which is about like public

client receiver get:
http://golang.org/pkg/net/http/#Client.Get

   func (c *Client) Get(url string) (resp *Response, err error)
        //^ this is the receiver

huangapple
  • 本文由 发表于 2015年8月18日 02:21:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/32057142.html
匿名

发表评论

匿名网友

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

确定