我正在阅读此博客文章http://www.hydrogen18.com/blog/golang-embedding.html,遇到了这些问题
There is an important distinction to observe here. If myParent is an instance of Parent the value myParent cannot act as a Valueable. You must use the the value &myParent, a pointer to the instance, to act as a Valueable. This is because the method Value receives a *Parent not a Parent.
我创建了一个示例https://play.golang.org/p/ojTKZfx97g。因此,问题在于为什么调用方法myparent.Value()本身可以工作,但通过interface
调用时却不起作用
根据有效执行,如果该值是可寻址的,则执行将自动插入
您的
1 2 3 | type Valueable interface { Value() int64 } |
您可以将实现此接口的任何值传递给它。您的
1 2 3 | func (i *Parent) Value() int64{ return i.value } |
并且根据Go语言规范(方法集和接口类型),
...The method set of any other type
T consists of all methods declared with receiver typeT . The method set of the corresponding pointer type*T is the set of all methods declared with receiver*T orT (that is, it also contains the method set ofT ).
因此类型
因此您可以将
1 | fmt.Println(callValueable(&myparent)) // This WORKS |
- 谢谢icza。我认为问题的症结在于为什么golang无法自动插入