GO - 为什么隐式非指针方法不满足接口? [英] GO - Why implicit non-pointer methods not satisfy interface?
问题描述
假设我们已经理解了,
对于
X $ c $类型的显式方法定义如果我声明,那么GO编译器为
* X
和反过来隐式定义了相同的方法,func(c Cat)foo(){
// do stuff_
}
并声明,
func(c * Cat)然后GO编译器提供给foo(){
// do stuff_
}
错误,
编译错误:重新声明方法
这表明,指针方法是隐式定义的,反之亦然
在下面的代码中,
package main
类型X接口{
foo();
bar();
类型结构{
}
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 //确定; * Cat有显式方法bar()和隐式方法foo()
x = c //编译错误:cat有显式方法foo()和隐式方法bar()
}
GO编译器给出错误,
不能使用c(类型Cat)作为赋值中的类型X:
Cat没有实现X(bar方法有指针接收器)
at x = c
,因为隐式指针方法满足接口,但隐式的非指针方法不会。
问题:
为什么隐式非指针方法不满足接口?
让我们看看语言 specification :
类型可能有一个方法集与之相关联。接口类型
的方法是它的接口。任何其他
类型T的方法集包含所有使用接收方类型T声明的方法。相应的指针类型* T的
方法集合是所有使用接收方声明的
方法的集合* T或T(即也包含
的方法集合)。
在你的例子中,接口类型 x
的方法集是 [foo(),bar()]
。类型 Cat
的方法集合是 [foo()]
,类型为 * Cat
是 [foo()]
+ [bar()]
= [foo(),bar()]
。
这解释了为什么变量 p
满足界面 x
,但变量 c
不会。
Assuming we have an understanding that,
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_ }
and declare,
func (c *Cat) foo(){ // do stuff_ }
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 compiler gives error,
cannot use c (type Cat) as type X in assignment:
Cat does not implement X (bar method has pointer receiver)
at x = c
, because, implicit pointer methods satisfy interfaces, but implicit non-pointer methods do not.
Question:
Why implicit non-pointer methods do not satisfy interfaces?
Let's look into the language specification:
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).
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()]
.
This explains, why variable p
satisfies the interface x
, but variable c
doesn't.
这篇关于GO - 为什么隐式非指针方法不满足接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!