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

Mat*_*att 5 struct pointers interface 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
}
Run Code Online (Sandbox Code Playgroud)

难道VegetableSalt两个满足Food,即使一个是一个指针,另一个是直接一个结构?

zzz*_*zzz 14

通过编译代码很容易得到答案:

prog.go:19: invalid receiver type Vegetable (Vegetable is a pointer type)
Run Code Online (Sandbox Code Playgroud)

该错误基于以下规格要求:

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

(强调我的)

声明:

type Vegetable *vegetable_s
Run Code Online (Sandbox Code Playgroud)

声明一个指针类型,即.Vegetable不符合方法接收者的资格.

  • 有谁知道为什么这样设计? (11认同)