调用接口方法和结构体方法在serveHTTP处理程序中有什么区别?

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

What is the difference in calling an interface methods and struct methods in serveHTTP handler?

问题

我正在从Java转向Go语言。在Go语言中,当使用Handler时,我感到困惑。

例如:ServeHTTP(w http.ResponseWriter, req *http.Request)

这里的ResponseWriter是一个接口,Request是一个结构体。我们使用w作为对象来调用ResponseWriter接口中的方法,req对象也是一样。我知道结构体可以实现接口。这里我展示了一个例子,我在这个例子中感到困惑。Go Playground链接

英文:

I'm moving from Java to go. In 'go', I got confused when using a Handler.

For eg: ServeHTTP(w http.ResponseWriter, req *http.Request)

Here ResponseWriter is an interface and Request is a struct. We are using w as an object to call the methods in ResponseWriter interface. The same goes with req object. I know that a struct can implement an interface. Here I'm showing an example and where I'm getting confused. Go Playground Link

答案1

得分: 2

没有区别。接口是你的变量/字段/参数的类型;值仍然是(很可能是)一个结构体。这与Java中的情况相同,你可以指定一个方法参数是接口类型,但你仍然必须传入一个具体实现。在接口类型的参数上调用方法与在具体类型上调用方法是相同的。

英文:

There's no difference. The interface is the type of your variable/field/parameter; the value is still (most likely) a struct. This is the same as in Java, where you can specify that a method argument is of an interface type, but you must still pass in a concretion. Calling methods on the interface-typed argument is the same as calling the method on a concrete type.

huangapple
  • 本文由 发表于 2017年6月17日 01:11:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/44594659.html
匿名

发表评论

匿名网友

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

确定