-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpolymorphism.go
79 lines (64 loc) · 1.46 KB
/
polymorphism.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
package main
import "fmt"
const (
PROTOCOL_TYPE_CLIENT = iota
PROTOCOL_TYPE_SERVER
)
type IProtocol interface {
Type() int
Run() error
}
type Protocol struct {
Id int
}
type ClientProtocol struct {
Protocol
Username string
}
type ServerProtocol struct {
Protocol
IsUp bool
}
func (p *ClientProtocol) Type() int {
return PROTOCOL_TYPE_CLIENT
}
func (p *ClientProtocol) Run() error {
fmt.Println("I'm a client with id =", p.Id)
return nil
}
func (p *ServerProtocol) Type() int {
return PROTOCOL_TYPE_SERVER
}
func (p *ServerProtocol) Run() error {
fmt.Println("I'm a server with id =", p.Id)
return nil
}
func main() {
client := ClientProtocol{Username: "mahdiz", Protocol: Protocol{Id: 76}}
server := ServerProtocol{IsUp: true, Protocol: Protocol{Id: 248}}
protocols := [2]IProtocol{&client, &server}
protocols[0].Run()
protocols[1].Run()
for _, p := range protocols {
switch p.Type() {
case PROTOCOL_TYPE_CLIENT:
cp, _ := p.(*ClientProtocol) // Type assertion
fmt.Println("Client username:", cp.Username)
fmt.Println("Client id:", cp.Id)
case PROTOCOL_TYPE_SERVER:
sp, _ := p.(*ServerProtocol) // Type assertion
fmt.Println("Server is up?", sp.IsUp)
fmt.Println("Server id:", sp.Id)
}
}
var anything [2]interface{}
anything[0] = client
anything[1] = server
ca, ok := anything[0].(ClientProtocol) // Type assertion
if ok {
fmt.Println(ca.Username)
fmt.Println(ca.Id)
} else {
fmt.Println("Not a client protocol!")
}
}