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

时间:2013-07-27 20:25:35

标签: pointers interface struct go

例如,在以下示例中:

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
}

VegetableSalt是否都满足Food,即使一个是指针而另一个直接是结构?

2 个答案:

答案 0 :(得分:13)

答案很容易通过compiling the code获得:

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

错误基于specs要求:

  

接收器类型必须是T或* T形式,其中T是类型名称。由T表示的类型称为接收器基类型; 它不能是指针或接口类型,它必须在与方法相同的包中声明。

(强调我的)

宣言:

type Vegetable *vegetable_s

声明指针类型,即。 Vegetable不符合方法接收者的条件。

答案 1 :(得分:0)

您可以执行以下操作:

package main

type Food interface {
    Eat() bool
}

type vegetable_s struct {}
type Vegetable vegetable_s
type Salt struct {}

func (p *Vegetable) Eat() bool {return false}
func (p Salt) Eat() bool {return false}

func foo(food Food) {
   food.Eat()
}

func main() {
    var f Food
    f = &Vegetable{}
    f.Eat()
    foo(&Vegetable{})
    foo(Salt{})
}