假设我们有一个理解,
对于 type 的显式方法定义
X
,GO 编译器为 type 隐式定义相同的方法,*X
反之亦然,如果我声明,func (c Cat) foo(){ //do stuff_ }
并声明,
func (c *Cat) foo(){ // do stuff_ }
然后 GO 编译器给出错误,
Compile error: method re-declared
这表明,指针方法是隐式定义的,反之亦然
在下面的代码中,
package main
type X interface{
foo();
bar();
}
type Cat struct{
}
func (c Cat) foo(){
// do stuff_
}
func (c *Cat) bar(){
// do stuff_
}
func main() {
var c Cat
var p *Cat
var x X
x = p // OK; *Cat has explicit method bar() and implicit method foo()
x = c //compile error: Cat has explicit method foo() and implicit method bar()
}
GO 编译器报错,
cannot use c (type Cat) as type X in assignment:
Cat does not implement X (bar method has pointer receiver)
at x = c
,因为隐式指针方法满足接口,但隐式非指针方法不满足。
问题:
为什么隐式非指针方法不满足接口?