好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

golang类型判断x.(T)和reflect.TypeOf(x)

1.类型识别
var data interface{} = "hello"
strValue, ok := data.(string)
if ok {
fmt.Printf("%s is string type\n", strValue)
}
T的类型并不是任意的,比如有如下json
var f interface{}
b := []byte(`[{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}]`)
json.Unmarshal(b, &f)
data, ok := f.([]interface{})    // 这里不能使用f.([]map[string]interface{}),这样是无法判断成功的
if ok {
fmt.Printf("%+v\n", data)
return
}

2.类型获取
var str string = “hello”
fmt.Println(reflect.TypeOf(str))

3.类型判断
var f interface{}
b := []byte(`[{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}]`)
json.Unmarshal(b, &f)
for k, v := range f.(map[string]interface{}) {
switch vv := v.(type) {
case string:
fmt.Println(k, "is string", vv)
case int:
fmt.Println(k, "is int ", vv)
case float64:
fmt.Println(k, "is float64 ", vv)
case []interface{}:
fmt.Println(k, "is array:")
for i, j := range vv {
fmt.Println(i, j)
}
}
}

通过以上三种方法,基本上可以满足golang中对类型的动态识别、获取和判断操作了。

查看更多关于golang类型判断x.(T)和reflect.TypeOf(x)的详细内容...

  阅读:46次

上一篇: Golang String 常用中文API

下一篇:没有了