package main
import "fmt"
type Point struct {
x int
y int
}
func TypeJudge(items ...interface{}) {
for i, x := range items {
switch x.(type) {
case bool:
fmt.Printf("第%d个参数%v是bool类型n", i, x)
case int, int32, int64:
fmt.Printf("第%d个参数%d是数字类型n", i, x)
case string:
fmt.Printf("第%d个参数%s是string类型n", i, x)
case Point:
fmt.Printf("第%d个参数%v是Point类型n", i, x)
case *Point:
fmt.Printf("第%d个参数%v是*Point类型n", i, x)
default:
fmt.Printf("第%d个参数%v类型不确定n", i, x)
}
}
}
func main() {
var a interface{}
var point Point = Point{
x: 1,
y: 2,
}
a = point
var b Point
// 类型断言,如果类型不匹配会panic
b = a.(Point)
fmt.Println(b)
var c Point
// 类型断言失败时不会panic
c, ok := a.(Point)
if ok {
fmt.Println("convert ok, c:", c)
} else {
fmt.Println("convert fail")
}
a1 := "hello"
a2 := true
var a3 int = 60
var a4 int64 = 60
TypeJudge(a1, a2, a3, a4, b, &c)
}
类似Java中得instanceof
以上代码输出如下
{1 2}
convert ok, c: {1 2}
第0个参数hello是string类型
第1个参数true是bool类型
第2个参数60是数字类型
第3个参数60是数字类型
第4个参数{1 2}是Point类型
第5个参数&{1 2}是*Point类型



