为什么隐式非指针方法不能满足接口? [英] Why implicit non-pointer methods not satisfy interface?
问题描述
假设我们了解到,
Assuming we have an understanding that,
对于类型X
的显式方法定义,如果我声明,GO编译器将为类型*X
和反之亦然隐式定义相同的方法
For explicit method definition for type X
, GO compiler implicitly defines the same method for type *X
and vice versa, if I declare,
func (c Cat) foo(){
//do stuff_
}
并声明,
func (c *Cat) foo(){
// do stuff_
}
然后,GO编译器会给出错误消息,
then GO compiler gives error,
Compile error: method re-declared
表示隐式定义了指针方法,反之亦然
which indicates that, pointer method is implicitly defined and vice versa
在下面的代码中,
In the below code,
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编译器出现错误
GO compiler gives error,
cannot use c (type Cat) as type X in assignment:
Cat does not implement X (bar method has pointer receiver)
在x = c
,因为隐式指针方法满足接口,但隐式非指针方法不满足接口.
at x = c
, because, implicit pointer methods satisfy interfaces, but implicit non-pointer methods do not.
问题:
为什么隐式非指针方法不满足接口?
Why implicit non-pointer methods do not satisfy interfaces?
推荐答案
让我们研究一下语言规范:
一种类型可能具有与之关联的方法集.方法集 接口类型的名称是其接口.其他方法集 类型T包含以接收者类型T声明的所有方法. 对应的指针类型* T的方法集是所有的集 用接收者* T或T声明的方法(即还包含 T的方法集.
A type may have a method set associated with it. The method set of an interface type is its interface. The method set of any other type T consists of all methods declared with receiver type T. The method set of the corresponding pointer type *T is the set of all methods declared with receiver *T or T (that is, it also contains the method set of T).
在您的示例中,接口类型为x
的方法集为[foo(), bar()]
.类型为Cat
的方法组为[foo()]
,类型为*Cat
的方法组为[foo()]
+ [bar()]
= [foo(), bar()]
.
In your example, the method set of the interface type x
is [foo(), bar()]
. The method set of the type Cat
is [foo()]
, and the method set of the type *Cat
is [foo()]
+ [bar()]
= [foo(), bar()]
.
这说明了为什么变量p
满足接口x
但变量c
不满足的原因.
This explains, why variable p
satisfies the interface x
, but variable c
doesn't.
这篇关于为什么隐式非指针方法不能满足接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!