-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInterfaces.go
124 lines (92 loc) · 1.97 KB
/
Interfaces.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package main
import (
"fmt"
)
type shape interface {
Area() float64
Perimeter() float64
}
type Duck interface {
Talk() string
Walk()
Swim()
}
type Dog struct {
name string
}
/* all what Duck can is being a Duck */
func (d Dog) Talk() string {
return "ARRRRRRR"
}
func (d Dog) Walk() {}
func (d Dog) Swim() {}
func quack(d Duck) {
fmt.Println(d.Talk())
}
/* неявные интерфейсы */
type MyStringer struct{ s string }
func (s MyStringer) String() string {
return "MyStringer" + s.s
}
type Stringer interface {
String() string
}
/* type can implement several interfaces */
type Hound interface {
Hunt()
}
type Poodle interface {
Bark()
}
type GoldenRetriever struct{ name string }
func (GoldenRetriever) Hunt() { fmt.Println("hunt") }
func (GoldenRetriever) Bark() { fmt.Println("bark") }
func f1(i Hound) { i.Hunt() }
func f2(i Poodle) { i.Bark() }
/* one interface can have several types */
type Scandinav struct{ name string }
func (Scandinav) Bark() { fmt.Println("bark" + "-sc-" + "name") }
type ToyPoodle struct{ name string }
func (ToyPoodle) Bark() { fmt.Println("bark" + "-toy-" + "name") }
/* composition */
type Greeter interface {
Hello()
}
type Stranger interface {
Bye() string
Greeter
fmt.Stringer
}
/* empty interface */
// interface{}
func PrintAll(vals []interface{}) {
for _, val := range vals {
fmt.Println(val)
}
}
func main() {
log := Logger("Interfaces")
log("Interfaces tests start")
fmt.Println("Interfaces")
quack(Dog{})
fmt.Println(MyStringer{"Hello"})
t := GoldenRetriever{"Jack"}
f1(t)
f2(t)
var sc, toy Poodle
sc = Scandinav{"Tom"}
toy = ToyPoodle{"Russ"}
sc.Bark()
toy.Bark()
log("Empty interface - kinda generic")
vals := []interface{}{"John", "Pepe", "Huan"}
// /* need to be converted to the interface type */
names := []string{"asdf", "fda"}
vals2 := make([]interface{}, len(names))
for i, v := range names {
vals2[i] = v
}
PrintAll(vals)
PrintAll(vals2)
defer log("Interfaces tests end")
}