golang use reflect to judge type of variable

  • 众所周知,golang中可以使用空接口即interface{}代表任何类型的数据,那么在使用的时候,我们有时需要获取返回值的具体类型
  • 场景:beego框架中的orm.Params类型,实际上是map[string]interface{},在使用values接口的时候,需要从返回Map中获取数据,需要这样获取:Id:m["Id"].(string),这时m[“Id”]实际上是String类型,我们可以用reflect模块来获取实际的类型
1
2
reflect.TypeOf(m["Id"])
//返回为String
1
2
3
4
5
6
7
8
9
10
11
package main

import (
"fmt"
"reflect"
)

func main() {
var x int32 = 20
fmt.Println("type:", reflect.TypeOf(x))
}

-------------The End-------------

Title:golang use reflect to judge type of variable

Author:cloud sjhan

Publish Time:2018年12月25日 - 19:12

Last Update:2018年12月25日 - 19:12

Original Link:https://cloudsjhan.github.io/2018/12/25/golang-use-reflect-to-judge-type-of-variable/

License: By-NC-ND 4.0 international

cloud sjhan wechat
subscribe to my blog by scanning my public wechat account
keep going, keep coding
0%
;