golang-exercises/interfaces/main.go

49 lines
663 B
Go
Raw Normal View History

package main
import (
"fmt"
)
type Sounder interface {
AnimalSound()
}
type Cat struct {
sound string
}
type Dog struct {
sound string
}
type JavaProgrammer struct {
sound string
}
func (c Cat) AnimalSound() {
fmt.Println(c.sound)
}
func (d Dog) AnimalSound() {
fmt.Println(d.sound)
}
func (j JavaProgrammer) AnimalSound() {
fmt.Println(j.sound)
}
func MakeSound(s Sounder) {
s.AnimalSound()
}
func main() {
animals := []Sounder{Cat{sound: "Meow"}, Dog{sound: "Woof"}, JavaProgrammer{sound: "*Unintelligible*"}}
MakeSound(animals[2])
MakeSound(animals[1])
MakeSound(animals[0])
// for _, v := range animals {
// v.AnimalSound()
// }
}