golang 变量类型
1 // golang 查看变量的类型 2 // 1.switch 中使用i.(type) 3 // 2.使用反射 reflect.TypeOf(i) 4 package main 5 6 import ( 7 "fmt" 8 "reflect" 9 ) 10 11 func UseSwitch(i interface{}) { 12 switch i.(type) { 13 case int: 14 fmt.Println("switch:int") 15 case string: 16 fmt.Println("switch:string") 17 case int32: 18 fmt.Println("switch:int32") 19 default: 20 fmt.Println("default") 21 } 22 } 23 24 func UseReflect(i interface{}) { 25 fmt.Println("reflect:", reflect.TypeOf(i)) 26 } 27 28 func main() { 29 var i int32 = 1 30 var s = "ssss" 31 var ii int = 2 32 UseSwitch(i) 33 UseSwitch(s) 34 UseSwitch(ii) 35 UseReflect(i) 36 UseReflect(s) 37 UseReflect(ii) 38 }
输出:
switch:int32 switch:string switch:int reflect: int32 reflect: string reflect: int