zoukankan      html  css  js  c++  java
  • golang类型断言

    什么是类型断言

    因为接口是一般类型,不知道具体类型,如果要转成具体类型就要使用类型断言

    先看简单的(报错的代码)

    package main
    
    import "fmt"
    
    type Point struct {
    	x int
    	y int
    }
    
    func main() {
    	var a interface{}
    	p := Point{1,2}
    	a =p
    	var b Point
    	b = a//这里会报错
    	fmt.Println(b)
    }
    

     用类型断言,没用类型断言无法确定a就是Point类型:

    package main
    
    import "fmt"
    
    type Point struct {
    	x int
    	y int
    }
    
    func main() {
    	var a interface{}
    	p := Point{1,2}
    	a =p
    	var b Point
    	b = a.(Point)
    	fmt.Println(b)
    }
    

     再看一段:

    package main
    
    import "fmt"
    
    type Usb interface {
    	Start()
    	Stop()
    }
    
    type Phone struct {
    	name string
    }
    func (this Phone) Start() {
    	fmt.Println("the phone is start working ")
    }
    func (this Phone) Call() {
    	fmt.Println("calling..")
    }
    func (this Phone) Stop() {
    	fmt.Println("the phone is stop working")
    }
    
    type Camera struct {
    	name string
    }
    func (this Camera) Start() {
    	fmt.Println("Camera is start working")
    }
    func (this Camera) Stop() {
    	fmt.Println("Camera is stop")
    }
    
    type Computer struct {
    	
    }
    
    func (this Computer) Working(usb Usb)  {
    	usb.Start()
    	if phone,ok := usb.(Phone); ok {
    		phone.Call()
    	}
    	usb.Stop()
    }
    
    func main() {
    	c :=Computer{}
    	phone1 :=Phone{"小米"}
    	phone2 := Phone{"华为"}
    	camera := Camera{"索尼"}
    	var usbarr [3]Usb
    	usbarr[0] = phone1
    	usbarr[1] = phone2
    	usbarr[2] = camera
    	for _,v:= range usbarr {
    		c.Working(v)
    	}
    }
    

     运结果:

  • 相关阅读:
    HDU 1850 Being a Good Boy in Spring Festival
    UESTC 1080 空心矩阵
    HDU 2491 Priest John's Busiest Day
    UVALive 6181
    ZOJ 2674 Strange Limit
    UVA 12532 Interval Product
    UESTC 1237 质因子分解
    UESTC 1014 Shot
    xe5 android listbox的 TMetropolisUIListBoxItem
    xe5 android tts(Text To Speech)
  • 原文地址:https://www.cnblogs.com/cfc-blog/p/10392776.html
Copyright © 2011-2022 走看看