package main import ( "fmt" ) type USB interface { Name() string Connect() } type PhoneConnector struct { name string } func (pc PhoneConnector) Name() string { return pc.name } func (pc PhoneConnector) Connect() { fmt.Println("Connected:" + pc.name) } func Disconnect(usb USB) { if pc, ok := usb.(PhoneConnector); ok { fmt.Println("a usb Disconnected , and it's name is :" + pc.name) return } fmt.Println("unkown device") } func main() { var iphone USB iphone = PhoneConnector{"iphone"} iphone.Connect() Disconnect(iphone) }输出结果:
Connected:iphone a usb Disconnected , and it's name is :iphone
有疑问加站长微信联系(非本文作者)