为什么隐式非指针方法不能满足接口? [英] Why implicit non-pointer methods not satisfy interface?

查看:87
本文介绍了为什么隐式非指针方法不能满足接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们了解到,

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆