Skip to content

Instantly share code, notes, and snippets.

@BekirUzun
Created April 27, 2019 15:18
Show Gist options
  • Select an option

  • Save BekirUzun/81b21daabcd44de013caa1a8c021eff6 to your computer and use it in GitHub Desktop.

Select an option

Save BekirUzun/81b21daabcd44de013caa1a8c021eff6 to your computer and use it in GitHub Desktop.
Golang struct composition and polymorphism simple example
package main
import (
"fmt"
)
type IAnimal interface {
Talk()
Info()
}
type Animal struct {
name string
age int
}
type Cat struct {
Animal
x int
}
func (c Cat) Talk() {
fmt.Printf("Meoww..\n")
}
func (c Cat) Info() {
fmt.Printf("Cat name:%s age:%d x:%d \n", c.name, c.age, c.x)
}
func NewCat(name string, age int, x int) Cat {
return Cat{Animal{name, age}, x}
}
type Dog struct {
Animal
y int
}
func (d Dog) Talk() {
fmt.Printf("woof woof!\n")
}
func (d Dog) Info() {
fmt.Printf("Dog name:%s age:%d y:%d \n", d.name, d.age, d.y)
}
func NewDog(name string, age int, y int) Dog {
return Dog{Animal{name, age}, y}
}
func animalPrinter(animal IAnimal) {
animal.Info()
animal.Talk()
fmt.Printf("\n")
}
func main() {
var a1 IAnimal = NewCat("Sylvester", 6, 123)
var a2 IAnimal = NewDog("Hector", 12, 41)
animalPrinter(a1)
animalPrinter(a2)
}
PS D:\Code\go\src\playground> go run main.go
Cat name:Sylvester age:6 x:123
Meoww..
Dog name:Hector age:12 y:41
woof woof!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment