In Go, can both a type and a pointer to a type implement an interface?

本秂侑毒 提交于 2019-12-10 14:41:45

问题


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?


回答1:


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.




回答2:


You could do the following:

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{})
}


来源:https://stackoverflow.com/questions/17902127/in-go-can-both-a-type-and-a-pointer-to-a-type-implement-an-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!