基本介绍
由于接口是一般类型,不知道具体类型,如果要转成具体类型,就需要使用类型断言。
代码
// 此案例演示类型断言 assertpackage mainimport ("fmt")type Point struct {x inty int}func main() {// 定义空接口var a interface{}var point Point = Point{1, 2}a = point // OKfmt.Println("a = ", a)// 怎么把 空接口 赋值给 变量var b Point// cannot use a (type interface {}) as type Point in assignment: need type assertion// b = a // ERRb = a.(Point) // 类型断言/*b = a.(Point) // 类型断言表示判断 a 是否是指向 Point 类型的变量,(上面 a = point 代码,a已经指向了Point)如果是,就把 a 转换成 Point 类型,并赋给 b 变量否则,就报错 (把上面 a = point 代码 去掉,就报错,类型推导不出来)*/fmt.Println("b = ", b)// 类型断言 float32 - interface{}var m float32var x interface{}x = mn := x.(float32)fmt.Printf("n 类型: %T, 值: %v \n", n, n)// n 类型: float32, 值: 0// 带检测的类型断言n2, ok := x.(float64)if ok {fmt.Println("convert success")fmt.Printf("n2 类型: %T, 值: %v \n", n2, n2)} else {fmt.Println("convert error")}// panic: interface conversion: interface {} is float32, not float64/* if n2, ok := x.(float64); ok {} */fmt.Println("panic 之后还会执行吗")}
使用类型断言的时候,如果类型不匹配,就会报 panic 错误,因此在进行类型断言的时候,要确保原先空接口指向的就是要断言的类型。
