dongxi7704 2017-01-29 14:49
浏览 25
已采纳

为什么隐式非指针方法不能满足接口?

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?

  • 写回答

4条回答 默认 最新

  • doubei3312 2017-01-29 15:28
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?