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

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 , although one is a pointer and the other is a struct?

+4
source share
2 answers

The answer is easy to get from compile code :

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

The error is based on specifications :

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

(Emphasizes mine)

Ad:

 type Vegetable *vegetable_s 

declares a pointer type, i.e. Vegetable not suitable as a method receiver.

+12
source

You can 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{}) } 
0
source

Source: https://habr.com/ru/post/1493849/


All Articles