Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you declare that a type belongs to a marker interface?

If I have these types:

type Orange struct {
  Size float32
}

type Lemon struct {
   Color string
}

type Wood struct {
   Variety string
}

And that interface:

type Fruit interface {
}

How do I declare that Orange and Lemon are Fruit,
so that, elsewhere, a function may return only things who are of kind Fruit?
(Fruit being a marker interface).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To declare that a type belongs to a marker interface in Go, you need to explicitly state that the type implements the interface. In your case, to declare that Orange and Lemon types are of kind Fruit, you can do the following:

type Fruit interface {

}

type Orange struct {
Size float32

}

func (o Orange) MethodOfFruit() {

// Implement any methods of Fruit interface if required

}

type Lemon struct {

Color string

}

func (l Lemon) MethodOfFruit()
{

// Implement any methods of Fruit interface if required

}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading