One interface, several very different types.
What to build
A program where different creatures speak in their own way.
Requirements
- Define an interface
SpeakerwithSpeak() string, and types fordog,catandparrot. - Each input line is
KIND NAMEor, for a parrot,parrot NAME WORDS.... - A dog says
NAME says Woof, a cat saysNAME says Meow, and a parrot saysNAME says WORDS WORDS(the words twice, with a space between). - For any other kind print
unknown kind KIND.
Input
Line 1: n. Then n lines as described.
Output
n lines.
Constraints
1 ≤ n ≤ 30; every line has at most 60 characters; kinds are lower case.
Example
Input:
3
dog Rex
cat Tom
parrot Polly hello there
Output:
Rex says Woof
Tom says Meow
Polly says hello there hello there
Why it works
Each type has its own Speak method, so a slice of Speaker (or just a call on each one) prints different text for each type without any type checks in the loop.
Examples
Example 1 · Input
3 dog Rex cat Tom parrot Polly hello there
Expected output
Rex says Woof Tom says Meow Polly says hello there hello there
Example 2 · Input
2 fish Nemo dog Max
Expected output
unknown kind fish Max says Woof
Hints
Hint 1
Declare type Speaker interface { Speak() string } with types Dog, Cat and Parrot (the parrot has a phrase).
Hint 2
Read lines with bufio.Scanner and split each line with strings.Fields; the parrot's phrase is the rest of the line.
Solution
Show one correct solution (try it yourself first)
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
type Speaker interface {
Speak() string
}
type Dog struct{ Name string }
type Cat struct{ Name string }
type Parrot struct {
Name string
Phrase string
}
func (d Dog) Speak() string { return d.Name + " says Woof" }
func (c Cat) Speak() string { return c.Name + " says Meow" }
func (p Parrot) Speak() string {
return p.Name + " says " + p.Phrase + " " + p.Phrase
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
for scanner.Scan() {
f := strings.Fields(scanner.Text())
if len(f) < 2 {
continue
}
var s Speaker
switch f[0] {
case "dog":
s = Dog{f[1]}
case "cat":
s = Cat{f[1]}
case "parrot":
s = Parrot{f[1], strings.Join(f[2:], " ")}
default:
fmt.Println("unknown kind", f[0])
continue
}
fmt.Println(s.Speak())
}
}