go 结构体类型反射 type_assert
package main
import "fmt"
func test(a interface{}){
fmt.Printf("你好啊%#v==%v==%T==%p\n",a,a,a,&a)
// 将接口类型的变量转化为具体类型 加个OK 判断, 可以避免程序直接崩溃, ok=false 转行失败
s,ok := a.(int) // 所以要加ok 判断, 对于不是int类型的, 会直接崩溃 panic: interface conversion: interface {} is string, not int
if !ok {
fmt.Printf("%v can't vonvert to int\n",s)
}
if ok {
fmt.Println("转化为int ok>>",s)
return
}
str, ok := a.(string)
if ok{
fmt.Printf("%v 转化为str ok>>",str)
return
}
f, ok := a.(float32)
if ok {
fmt.Println("转化为float ok>>",f)
return
}
fmt.Println("can not define type of a")
}
func testInterface1(){
var a int =100
test(a)
var b string = "hello world"
test(b) // panic: interface conversion: interface {} is string, not int
}
func testInterface2(){
var a int =100
testSwitch(a)
var b string = "hello "
testSwitch(b)
}
// 缺点是要转2次
func testSwitch(a interface{}){
switch a.(type){
case string:
fmt.Printf("a is string, value :%v\n",a.(string))
case int:
fmt.Printf("a is int, value :%v\n",a.(int))
case int32:
fmt.Printf("a is int32, value :%v\n",a.(int32))
default:
fmt.Println("not support type\n")
}
}
// 更推荐使用这个
func testSwitch2(a interface{}){
switch v := a.(type){
case string:
fmt.Printf("a is string, value :%v\n",v)
case int:
fmt.Printf("a is int, value :%v\n",v)
case int32:
fmt.Printf("a is int32, value :%v\n",v)
default:
fmt.Println("not support type\n")
}
}
func testInterface3(){
var a int =100
testSwitch2(a)
var b string = "hello "
testSwitch2(b)
}
func main() {
testInterface1()
testInterface2()
testInterface3()
}
输出:
你好啊100==100==int==0xc0000361f0
转化为int ok>> 100
你好啊"hello world"==hello world==string==0xc000036210
0 can't vonvert to int
hello world 转化为str ok>>a is int, value :100
a is string, value :hello
a is int, value :100
a is string, value :hello
写入自己的博客中才能记得长久