GOLANG利用断言调用结构体内特有的方法-

package main
import(
    "fmt"
    _"sort"
    _"math/rand"
)
//多态的特征是通过接口来实现的
//多态形式之一:多态参数
type Usb interface{
    start()
    stop()
}
 
type Phone struct{
    Name string
}
type Camera struct{
    Name string
}
 
func (p Phone) start(){
    fmt.Println(p.Name,"开始工作了")
}
func (p Phone) stop(){
    fmt.Println(p.Name,"停止工作了")
}
func (p Phone) call(){
    fmt.Println(p.Name,"拥有语言功能")
}
func (c Camera) start(){
    fmt.Println(c.Name,"开始工作了")
}
func (c Camera) stop(){
    fmt.Println(c.Name,"停止工作了")
}
type Computer struct{
    Name string
}
func (com Computer) working(usb Usb){  //usb变量会根据传入的实际参数,来判断到底是phone还是camera
    // 通过usb接口变量来调用start和stop方法
    usb.start()
	usb.stop()
	//添加断言,判断usb.(Phone)是否传入的是Phone,如何不是返回flase给flag,如果是返回true,执行Phone.call()
	if mob, flag := usb.(Phone);flag{
		mob.call()
	}
}
 
func main(){
	var usbArry [4]Usb
	usbArry[0] = Phone{"小米——国产"}
	usbArry[1] = Phone{"红米——国产"}
	usbArry[2] = Camera{"创维相机国产"}
	usbArry[3] = Camera{"尼康相机国产"}
	var com Computer
	for _ , v := range usbArry {
		com.working(v)
		fmt.Println()
	}
}

 终端结果:

猜你喜欢

转载自www.cnblogs.com/swei/p/10838108.html