-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path12.interface.go
More file actions
100 lines (79 loc) · 2 KB
/
12.interface.go
File metadata and controls
100 lines (79 loc) · 2 KB
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
package main
import (
"fmt"
)
// type USB interface {
// Name() string
// Connect()
// }
type empty interface {
}
type Connecter interface {
Connect()
}
type USB interface {
Name() string
Connecter
}
type PhoneConnecter struct {
name string
}
type TVConnecter struct {
name string
}
func (pc PhoneConnecter) Name() string {
return pc.name
}
func (pc PhoneConnecter) Connect() {
fmt.Println("Connect:", pc.name)
}
func (tv TVConnecter) Connect() {
fmt.Println("Connect:", tv.name)
}
// func Disconnect(usb USB) { // 这里要求的是USB类型, 而USB是interface类型
// fmt.Println("Disconnect:", pc.Name())
// }
// func Disconnect(usb empty) { // 这里要求的是USB类型, 而USB是interface类型
// if pc, ok := usb.(PhoneConnecter); ok {
// fmt.Println("Disconnect:", pc.Name())
// return
// }
// fmt.Println("Unknown device")
// }
func Disconnect(usb interface{}) { // 这里要求的是USB类型, 而USB是interface类型
switch v := usb.(type) {
case PhoneConnecter:
fmt.Println("Disconnect:", v.Name())
default:
fmt.Println("Unknown device.")
}
}
func main() {
// var usb USB
// usb = PhoneConnecter{"PhoneConnector"}
pc := PhoneConnecter{"PhoneConnector"}
pc.Connect()
Disconnect(pc)
other := 1
Disconnect(other)
var con Connecter
con = Connecter(pc)
con.Connect()
pc.name = "pc"
// 注意观察下面输出
// 发现name还是"PhoneConnector", 不是上面修改后的"pc", 说明con是pc的复制品, 不是引用
con.Connect()
// con.Name() // error 转换为Connector类型后就不能非Connector的方法了
// 注意观察下面语句输出
// 这里con.(type)还是识别类型为PhoneConnector类型,因为数据类型没变, 上面变得是接口类型
Disconnect(con)
// tv := TVConnecter{"TVConnector"}
// var usb USB
// usb = USB(tv) // error: 由于tv没有实现USB接口, 所以不能强制转换
// usb.Connect()
var a interface{}
fmt.Println(a == nil)
var p *int = nil
a = p
fmt.Println(a == nil) // a虽然指向空指针, 但依然不是nil
}