Created
April 27, 2019 15:18
-
-
Save BekirUzun/81b21daabcd44de013caa1a8c021eff6 to your computer and use it in GitHub Desktop.
Golang struct composition and polymorphism simple example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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