一、类型断言
类型断言,由于接口是一般类型,不知道具体类型,如果要转成具体类型,就需要使用类型断言
package main
import "fmt"
type Point struct {
x int
y int
}
func main() {
var a interface{}
var point Point = Point{1, 2}
a = point
var b Point
//b = a //报错
//使用类型断言解决
b = a.(Point)
fmt.Println(b)
}
二、断言检测
package main
import "fmt"
func main() {
var t float32
var x interface{}
x = t
f,ok := x.(float32)
if ok == true {
fmt.Println("转换成功",f)
}else {
fmt.Println("转换失败")
}
}
三、练习
package main
import "fmt"
type Person struct {
}
//item... 可变参数
func TypeJudge(item... interface{}) {
for index, value := range item {
switch value.(type) {
case bool:
fmt.Printf("第%v个参数是bool类型,值是%v\n",index,value)
case string:
fmt.Printf("第%v个参数是string类型,值是%v\n",index,value)
case float32:
fmt.Printf("第%v个参数是float32类型,值是%v\n",index,value)
case float64:
fmt.Printf("第%v个参数是float64类型,值是%v\n",index,value)
case int:
fmt.Printf("第%v个参数是int类型,值是%v\n",index,value)
case int8:
fmt.Printf("第%v个参数是int8类型,值是%v\n",index,value)
case int16:
fmt.Printf("第%v个参数是int16类型,值是%v\n",index,value)
case int32:
fmt.Printf("第%v个参数是int32类型,值是%v\n",index,value)
case int64:
fmt.Printf("第%v个参数是int64类型,值是%v\n",index,value)
case uint:
fmt.Printf("第%v个参数是uint类型,值是%v\n",index,value)
case uint8:
fmt.Printf("第%v个参数是uint8类型,值是%v\n",index,value)
case uint16:
fmt.Printf("第%v个参数是uint16类型,值是%v\n",index,value)
case uint32:
fmt.Printf("第%v个参数是uint32类型,值是%v\n",index,value)
case uint64:
fmt.Printf("第%v个参数是uint64类型,值是%v\n",index,value)
case Person:
fmt.Printf("第%v个参数是Person类型,值是%v\n",index,value)
case *Person:
fmt.Printf("第%v个参数是*Person类型,值是%v\n",index,value)
default:
fmt.Printf("没有找到相匹配的类型\n",value)
}
}
}
func main() {
var n1 float32 = 22.2
var n2 float64 = 500.3
var n3 int = 100
add := "成都"
n4 := 22.2
var p Person
var per = &Person{}
TypeJudge(n1,n2,n3,n4,add,p,per)
}