Skip to content

Commit

Permalink
Example 7.
Browse files Browse the repository at this point in the history
  • Loading branch information
idexter committed May 3, 2019
1 parent 1a2b042 commit f07a436
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 6 deletions.
13 changes: 11 additions & 2 deletions animal/animal.go
Expand Up @@ -3,5 +3,14 @@ package animal
// implementation of Animal
type Dog struct{}

func (a Dog) Speaks() string { return "woof" }
func (a Dog) IsTrained() bool { return true }
func (d Dog) Speaks() string { return "woof" }
func (d Dog) IsTrained() bool { return true }
func (d Dog) Jump() string { return "jumps" }
func (d Dog) Sit() string { return "sit" }

type Cat struct{}

func (c Cat) IsTrained() bool { return false }
func (c Cat) Speaks() string { return "meow!" }
func (c Cat) Jump() string { return "meow!!" }
func (c Cat) Sit() string { return "meow!!!" }
8 changes: 8 additions & 0 deletions circus/circus.go
Expand Up @@ -2,6 +2,8 @@ package circus

const (
ActVoice = iota
ActSit
ActJump
)

type Speaker interface {
Expand All @@ -11,6 +13,8 @@ type Speaker interface {
type Animal interface {
Speaker
IsTrained() bool
Jump() string
Sit() string
}

type Tamer struct{}
Expand All @@ -21,6 +25,10 @@ func (t *Tamer) Command(action int, a Animal) string {
switch action {
case ActVoice:
return a.Speaks()
case ActSit:
return a.Sit()
case ActJump:
return a.Jump()
}
return ""
}
Expand Down
14 changes: 10 additions & 4 deletions main.go
Expand Up @@ -8,10 +8,16 @@ import (
)

func main() {
d := &animal.Dog{}
t := &circus.Tamer{}
t2 := &circus.Tamer{}
d := &animal.Dog{}

fmt.Println(t.Command(circus.ActVoice, d)) // woof
fmt.Println(t.Command(circus.ActVoice, t2)) // Error: *circus.Tamer does not implement circus.Animal
fmt.Println(t.Command(circus.ActVoice, d)) // "woof"
fmt.Println(t.Command(circus.ActJump, d)) // "jumps"
fmt.Println(t.Command(circus.ActSit, d)) // "sit"

t2 := &circus.Tamer{}
c := &animal.Cat{}
fmt.Println(t2.Command(circus.ActVoice, c)) // "meow"
fmt.Println(t2.Command(circus.ActJump, c)) // "meow!!"
fmt.Println(t2.Command(circus.ActSit, c)) // "meow!!!"
}

0 comments on commit f07a436

Please sign in to comment.