英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论