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

本文来自:开源中国博客

感谢作者:itfanr

查看原文:Go语言模拟实现接口

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。