golang 类型断言

案例:

package main

import(
	"fmt"
)
//声明接口
type Usb interface{
   //声明需要实现的方法
   //方法名(参数列表)返回值列表
   start()
   stop()
}


//方法实现start 和 stop 方法
type Phone struct{
}

func (phone Phone) start(){
	fmt.Println("手机连接开始。。。")
}

func (phone Phone) stop(){
	fmt.Println("手机链接结束。。。")
}

func (phone Phone) call(){
	fmt.Println("手机打电话。。。")
}



type Computer struct{
}

func (computer Computer) start(){
	fmt.Println("电脑连接开始。。。")
}

func (computer Computer) stop(){
	fmt.Println("电脑链接结束。。。")
}

//接口执行工作
type Working struct{

}

func (Working Working) GetWorking(usb Usb){
	usb.start()
	usb.stop()
	//只要Phone 中有call方法,所以同时调用时,会出现Computer没有call方法
	//所以此时需要使用 类型断言 来进行判断
	//usb.(Phone) 类型断言
	//phone , ok 是随意定义的 
	/*
	if p , ok := usb.(Phone); ok {
		p.call()
	}
	*/
	if phone , ok := usb.(Phone); ok {
		phone.call()
	}
}


func main(){
	working := Working{}
	phone := Phone{}
	computer := Computer{}
	//方法以形参的方式传入GetWorking中
	working.GetWorking(phone)
	working.GetWorking(computer)
}
package main

import(
	"fmt"
)

type Student struct{

}

func TypeJudge(items... interface{}){
	for i,v := range items{
		i += 1 
		switch v.(type) { //这里的type是一个关键字,固定写法
		case bool:
			fmt.Printf("param #%d is a bool 值是%v\n",i,v)
		case float64:
			fmt.Printf("param #%d is a float64 值是%v\n",i,v)
		case int,int64:
			fmt.Printf("param #%d is a int 值是%v\n",i,v)
		case nil:
			fmt.Printf("param #%d is a nil 值是%v\n",i,v)
		case string:
			fmt.Printf("param #%d is a string 值是%v\n",i,v)
		case Student:
			fmt.Printf("param #%d is a Student 值是%v\n",i,v)
		case *Student:
			fmt.Printf("param #%d is a *Student 值是%v\n",i,v)
		default:
			fmt.Printf("param #%d s type is unknown 值是%v\n",i,v)
		}
	}
}


func main(){
   n1 := 10.1
   n2 := 30
   n3 := "aaaa"
   n4 := true
   n5 := 20.3

   stu1 := Student{}
   stu2 := &Student{}
   TypeJudge(n1,n2,n3,n4,n5,stu1,stu2)
   /*
    param #1 is a float64 值是10.1
	param #2 is a int 值是30      
	param #3 is a string 值是aaaa 
	param #4 is a bool 值是true   
	param #5 is a float64 值是20.3
	param #6 is a Student 值是{}  
	param #7 is a *Student 值是&{}
   */
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值