zoukankan      html  css  js  c++  java
  • 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

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

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

     

  • 相关阅读:
    django模型系统(二)
    css基础
    css进阶
    django模型系统(一)
    自定义过滤器及标签
    django模板标签
    模板变量及模板过滤器
    第六章 异常
    第三章:多态
    第三章:提高系统性能:从数据访问开始
  • 原文地址:https://www.cnblogs.com/superxuezhazha/p/14337105.html
Copyright © 2011-2022 走看看