go语言多态中的类型断言

发布时间 2024-01-12 20:59:00作者: 远洪

类型断言案例

package main

import (
    "fmt"
)

type Usb interface{
    Connect()
    DisConnect()
}

type Phone struct{
    Name string
}

/*
*  Phone实现了Usb 接口(是指实现了Usb接口的所有方法)
*/
func(p Phone) Connect(){
    fmt.Println("手机连接...")
}

func(p Phone) DisConnect(){
    fmt.Println("手机断开连接...")
}
// Phone 类中多了一个 Call 方法
func(p Phone) Call(){
    fmt.Println("手机打电话")
}

type Camera struct{
    Name string
}

func(c Camera) Connect(){
    fmt.Println("相机连接...")
}

func(c Camera) DisConnect(){
    fmt.Println("相机断开连接...")
}

type  Computer struct{
}

func(c Computer) Working(u Usb){     //  这里就提现了一个多态的实现 (①里提现为多态参数)
    u.Connect()

    // 这里使用了类型断言,当 u 为Phone 的时候,可以调用 Call方法
    if phone, ok := u.(Phone); ok == true {
        phone.Call()
    }

    u.DisConnect()
}

func main(){
    phone := Phone{"手机"}
    camera := Camera{"相机"}
    computer := Computer{}
    computer.Working(phone)    
    computer.Working(camera)

    var ar [2]Usb     // 多态数组的提现 ar 中放了两个不同的结构体
    ar[0] = phone
    ar[1] = camera
    fmt.Println(ar)
}