Created
March 14, 2021 05:40
-
-
Save Ja7ad/1f167c5d30a3e54cf1f25437efc1c18a to your computer and use it in GitHub Desktop.
polymorphism example for golang
This file contains 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 Speaker interface { | |
Speak() string | |
} | |
type cat struct {} | |
type dog struct {} | |
type person struct { | |
name string | |
} | |
func (c cat) Speak() string { | |
return "Meow..." | |
} | |
func (receiver dog) Speak() string { | |
return "Woof..." | |
} | |
func (p person) Speak() string { | |
return "Hi my name is " + p.name | |
} | |
func saySomethings(say ...Speaker) { | |
for _, s := range say { | |
fmt.Println(s.Speak()) | |
} | |
} | |
func emptyDetails(s interface{}) { | |
fmt.Printf("(%V, %T)\n", s, s) | |
} | |
func main() { | |
c := cat{} | |
d := dog{} | |
p := person{"javad"} | |
saySomethings(c,d,p) | |
emptyDetails(p) | |
emptyDetails(2) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment