一、interface
1 package main 2 3 import "fmt" 4 5 type USB interface { 6 Name() string 7 Connect() 8 } 9 10 type PhoneConnecter struct { 11 name string 12 } 13 14 func (pc PhoneConnecter) Name() string { 15 return pc.name 16 } 17 18 func (pc PhoneConnecter) Connect() { 19 fmt.Println(pc.name) 20 } 21 22 func main() { 23 var a USB 24 // 将结构体实例赋值给interface 25 // interface的value为PhoneConnecter的实例 26 a = PhoneConnecter{"PhoneConnecter"} 27 a.Connect() 28 DisConnect(a) 29 DisConnect2(a) 30 } 31 32 func DisConnect(usb USB) { 33 fmt.Println("DisConnect") 34 if pc, ok := usb.(PhoneConnecter); ok { 35 fmt.Println("DisConnect:", pc.name) 36 return 37 } 38 fmt.Println("unkown device") 39 } 40 41 func DisConnect2(usb interface{}) { 42 fmt.Println("DisConnect2") 43 switch v := usb.(type) { 44 case PhoneConnecter: 45 fmt.Println("DisConnect:", v.name) 46 default: 47 fmt.Println("unkown device") 48 } 49 }