GO语言使用之类型断言

一、基本介绍

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

二、快速入门案例

//类型断言
func TypeAssertion()  {
    var t float32 = 1.2
    var x interface{}
    x = t //ok

    //待检测的类型断言
    y , res := x.(float32)
    if res {
        fmt.Println("断言成功!", y)
    } else {
        fmt.Println("断言失败!")
    }

    y1 ,res1 := x.(int32)//转成float
    if res1 {
        fmt.Println("断言成功!", y1)
    } else {
        fmt.Println("断言失败!")
    }

}

三、类型断言的最佳实践

1、在前面【GO语言使用之面向对象编程(8)面向对象三大特征之多态】的Usb接口案例做改进:
给Phone结构体增加一个特有的方法call(), 当Usb 接口接收的是Phone 变量时,还需要调用call方法.

/*最佳实践1*/
//类型断言使用
func (p phone) call(){
    fmt.Printf("%s手机正在通话。。。。\n",p.name)
}
func (c camputer) working1(usb Usb)  {
    // 开始使用类型断言来调用Phone特有的方法Call
    ps ,yes :=usb.(phone)
    if yes {
        ps.call()
    }
    usb.boot()
    usb.shutdown()
    usb.charging()
}
func TypeAssertion1()  {    
    p := phone{"小米"}
    c := camera{"尼康"}
    cap := camputer{}
    cap.working1(p)
    cap.working1(c)
}

2、写一函数,循环判断传入参数的类型

/*最佳实践2*/
func TypeAssertion2()  {
    var t interface{}  // 这个是一个空接口
    var n int32 = 80 //
    t = n // 将  n 赋值给 t

    //写一代码,判断 t究竟指向什么类型 type-switch 又叫 类型断言
    // i := t.(type)  有两个作用
    // (1) 先尝试将 t 转成实际指向的数据类型
    // (2) 如果转成功,就会将实际指向的值,赋给 i
    // (3)
    switch i := t.(type) { // 
        case float32 :
            fmt.Printf("i的类型%T i的值%v\n", i, i)
        case float64 :
            fmt.Printf("i的类型%T i的值%v\n", i, i)
        case int32 :
            fmt.Printf("i的类型%T i的值%v\n", i, i)
        case bool :
            fmt.Printf("i的类型%T i的值%v\n", i, i)
        case string :
            fmt.Printf("i的类型%T i的值%v\n", i, i)
       //case Phone: //...
        default :
            fmt.Println("类型不确定")
    }

}

猜你喜欢

转载自blog.csdn.net/TDCQZD/article/details/81712807