ove*_*nge 5 methods interface go structural-typing
假设我们有这样的理解,
用于类型明确的方法定义
X,GO编译器隐式定义了相同的方法类型*X和反之亦然,如果我声明,Run Code Online (Sandbox Code Playgroud)func (c Cat) foo(){ //do stuff_ }并声明,
Run Code Online (Sandbox Code Playgroud)func (c *Cat) foo(){ // do stuff_ }然后GO编译器给出错误,
Run Code Online (Sandbox Code Playgroud)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()
}
Run Code Online (Sandbox Code Playgroud)
GO 编译器报错,
cannot use c (type Cat) as type X in assignment:
Cat does not implement X (bar method has pointer receiver)
Run Code Online (Sandbox Code Playgroud)
at x = c,因为隐式指针方法满足接口,但隐式非指针方法不满足。
题:
为什么隐式非指针方法不满足接口?