-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanimals.go
65 lines (55 loc) · 1.14 KB
/
animals.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main
import (
"fmt"
"strings"
)
func main() {
animals := map[string]Animal{
"cow": CreateAnimal("grass", "walk", "moo"),
"bird": CreateAnimal("worms", "fly", "peep"),
"snake": CreateAnimal("mice", "slither", "hsss"),
}
for {
fmt.Printf(">")
// scan user input
var animalName, animalInfo string
fmt.Scan(&animalName, &animalInfo)
animal, animalPresent := animals[animalName]
if animalPresent {
switch strings.ToLower(animalInfo) {
case "eat":
fmt.Println(animal.Eat())
case "move":
fmt.Println(animal.Move())
case "speak":
fmt.Println(animal.Speak())
default:
fmt.Println("Invalid action")
}
} else {
fmt.Println("Invalid animal")
}
}
}
type Animal struct {
food, locomotion, noise string
}
func (a *Animal) init(food, locomotion, noise string) {
a.food = food
a.locomotion = locomotion
a.noise = noise
}
func CreateAnimal(food, locomotion, noise string) Animal {
var a Animal
a.init(food, locomotion, noise)
return a
}
func (a *Animal) Eat() string {
return a.food
}
func (a *Animal) Move() string {
return a.locomotion
}
func (a *Animal) Speak() string {
return a.noise
}