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