forked from BruceEckel/OnJava8-Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpetspeak.go
More file actions
51 lines (43 loc) · 994 Bytes
/
petspeak.go
File metadata and controls
51 lines (43 loc) · 994 Bytes
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
// staticchecking/petspeak.go
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
package main
import "fmt"
type Cat struct {}
func (this Cat) speak() { fmt.Printf("meow!\n")}
type Dog struct {}
func (this Dog) speak() { fmt.Printf("woof!\n")}
type Bob struct {}
func (this Bob) bow() {
fmt.Printf("thank you, thank you!\n")
}
func (this Bob) speak() {
fmt.Printf("Welcome to the neighborhood!\n")
}
func (this Bob) drive() {
fmt.Printf("beep, beep!\n")
}
type Speaker interface {
speak()
}
func command(s Speaker) { s.speak() }
// If "Speaker" is never used
// anywhere else, it can be anonymous:
func command2(s interface { speak() }) { s.speak() }
func main() {
command(Cat{})
command(Dog{})
command(Bob{})
command2(Cat{})
command2(Dog{})
command2(Bob{})
}
/* Output:
meow!
woof!
Welcome to the neighborhood!
meow!
woof!
Welcome to the neighborhood!
*/