-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterfaces.go
More file actions
53 lines (48 loc) · 842 Bytes
/
interfaces.go
File metadata and controls
53 lines (48 loc) · 842 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
52
53
package main
import "fmt"
// Similar to inheritance via structs, interfaces allow
// different structs to share functionality
type walkable interface {
attachLeash()
walk()
}
type talkable interface {
talk()
}
func (d *dog) attachLeash() {
fmt.Println(d.leash)
}
func (d *dog) walk() {
fmt.Println("all goes well")
}
func (d *dog) talk() {
fmt.Println(d.sound)
}
func (c *cat) attachLeash() {
fmt.Println(c.leash)
}
func (c *cat) walk() {
fmt.Println("this was a bad idea")
}
func (c *cat) talk() {
fmt.Println(c.sound)
}
func (b *bird) talk() {
fmt.Println(b.sound)
}
func interfaces() {
speak(&fido)
walkPet(&fido)
speak(&felix)
walkPet(&felix)
//cant walk an eagle, won't compile
//walkPet(&eagle)
speak(&eagle)
}
func speak(pet talkable) {
pet.talk()
}
func walkPet(pet walkable) {
pet.attachLeash()
pet.walk()
}