Skip to content

Instantly share code, notes, and snippets.

@Ja7ad
Created March 14, 2021 05:40
Show Gist options
  • Save Ja7ad/1f167c5d30a3e54cf1f25437efc1c18a to your computer and use it in GitHub Desktop.
Save Ja7ad/1f167c5d30a3e54cf1f25437efc1c18a to your computer and use it in GitHub Desktop.
polymorphism example for golang
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