Go语言模拟实现接口

 
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
   

转载于:https://my.oschina.net/itfanr/blog/195645

猜你喜欢

转载自blog.csdn.net/weixin_34392435/article/details/91799352