不是很明白类型断言干嘛用的,现在看来的话,可以用来做类型判断,先做个笔记

 

go 类型断言_基本数据类型

 

 go 类型断言_基本数据类型_02

 

 来一个小例子

go 类型断言_基本数据类型_03go 类型断言_基本数据类型_04
package main

import "fmt"

type Usb interface{
    

    start()
    stop()
}

type Phone struct {

}
type Caramera struct {

}

func (p Phone) start()  {
    fmt.Println("phone start")
}
func (p Phone) stop()  {
    fmt.Println("phone stop")
}
func (p Phone) call()  {
    fmt.Println("phone call")
}
func (p Caramera) start()  {
    fmt.Println("caramera start")
}
func (p Caramera) stop()  {
    fmt.Println("caramera stop")
}

type Computer struct {

}

func (c Computer) working(usb Usb)  {
    usb.start()
    if phone,ok := usb.(Phone);ok{
        phone.call()
    }
    usb.stop()
}

func main() {

    var usbArray [3]Usb

    usbArray[0] = Phone{}
    usbArray[1] = Phone{}
    usbArray[2] = Caramera{}

    c:=Computer{}
    for _,v := range  usbArray{
        c.working(v)
    }
}
View Code

我们利用类型断言,判断传入的变量的类型

go 类型断言_基本数据类型_05

 

 在来一个基本数据类型的判断

go 类型断言_基本数据类型_06

 

 go 类型断言_基本数据类型_07