doqs8936 2013-07-27 20:25
浏览 228
已采纳

在Go中,类型和指向类型的指针都可以实现接口吗?

For example in the following example:

type Food interface {
    Eat() bool
}

type vegetable_s struct {
    //some data
}

type Vegetable *vegetable_s

type Salt struct {
    // some data
}

func (p Vegetable) Eat() bool {
    // some code
}

func (p Salt) Eat() bool {
    // some code
}

Do Vegetable and Salt both satisfy Food, even though one is a pointer and the other is directly a struct?

  • 写回答

2条回答 默认 最新

  • dongwei2882 2013-07-27 20:36
    关注

    The answer is easy to get by compiling the code:

    prog.go:19: invalid receiver type Vegetable (Vegetable is a pointer type)
    

    The error is based on the specs requirement of:

    The receiver type must be of the form T or *T where T is a type name. The type denoted by T is called the receiver base type; it must not be a pointer or interface type and it must be declared in the same package as the method.

    (Emphasizes mine)

    The declaration:

    type Vegetable *vegetable_s
    

    declares a pointer type, ie. Vegetable is not eligible as a method receiver.

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

报告相同问题?

悬赏问题

  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据