I like the answers here so far, and I want to add one that allows you to do static type checking on the interface that you pass using the interface:
package main import ( "fmt" ) type Animalizer interface { GetColour() string } type Animal struct { Colour string Name string } type Dog struct { Animal } func (a *Animal) GetColour() string { return a.Colour } func PrintColour(a Animalizer) { fmt.Print(a.GetColour()) } func main() { a := new(Animal) a.Colour = "Void" d := new(Dog) d.Colour = "Black" PrintColour(a) PrintColour(d) }
On the playground
You can add additional fields to Dog . The difference with Uriel Answer is that PrintColour calls PrintColour not be executed at compile time if something else is passed than the implementation of struct Animalizer .
In addition, you will not need to use typwitch, as the compiler knows that Animalizer implements GetColour .
And finally, the behavior (printing) is separated from the structure, GetColour simply returns the color.
Beat richartz
source share