英文:
Calling methods on interface pointers in Go
问题
我还在努力理解Go语言中接口和指针的细节。我遇到了一个问题,涉及一个包含指向net.Conn的指针的简单类型。当我尝试在指针上调用一个方法(Close)时,我收到了type *net.Conn has no field or method Close
的错误信息。
这里有一个简单的示例来突出这个问题:http://play.golang.org/p/Q4LB0wi6Tk
在这种情况下,正确的调用Close()
的方式是什么?
英文:
I'm still sort of wrapping my head around the finer details of interfaces and pointers in Go. I've run into an issue with a simple type containing a pointer to net.Conn. When I attempt to call a method (Close) on the pointer, I'm receiving type *net.Conn has no field or method Close
Here's a trivial example highlighting the issue: http://play.golang.org/p/Q4LB0wi6Tk
What's the proper way to call Close()
here?
答案1
得分: 13
简短回答是“不要使用指向接口的指针”。很少有必要使用它们,而且你最终会遇到像你所看到的混淆错误。
你也不会使用new()
来创建一个指向空接口的指针。接口通过具体类型隐式满足。
英文:
Short answer is "Don't use pointers to interfaces". There's rarely any need for them, and you end up with confusing errors like you see.
You would also never use new()
to create a pointer to an empty interface. Interfaces are satisfied implicitly by a concrete type.
答案2
得分: 10
一个 net.Conn 是一个小的(两个字)结构体。如果实现是一个指针,那么持有该实现的 net.Conn 也像一个指针一样。请参考 http://research.swtch.com/interfaces 了解接口在底层是如何工作的。
英文:
A net.Conn is a small (two-word) structure. If the implementation is a pointer, then the net.Conn holding that implementation is like a pointer too. See http://research.swtch.com/interfaces for an description of how interfaces work under the hood.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论