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

 

go 类型断言

 

 go 类型断言

 

 来一个小例子

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

相关文章:

  • 2021-10-30
  • 2021-05-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-20
  • 2021-07-03
猜你喜欢
  • 2021-12-20
  • 2022-01-21
  • 2022-12-23
  • 2022-12-23
  • 2021-06-03
  • 2022-12-23
  • 2021-08-20
相关资源
相似解决方案