golang数据的类型识别、获取与判断

栏目: Go · 发布时间: 7年前

### golang数据的类型识别、获取与判断

golang是一种简洁、方便、效率高的语言,很适合C/C++、 Python程序员 使用。

golang是静态语言,但是具有动态语言的特性,这篇文章主要介绍golang的数据类型在运行期的识别、获取和判断方法,让大家可以感受到golang静态语言的动态特性。

#### 1.类型识别

在我们编码中,经常会碰到读取数据时,要判断数据是哪种类型,典型的是json格式文本的读取和识别。在golang中主要用 x.(T)的方式来识别类型:x是变量,而且是不确定类型的变量,interface,如果是已知类型的,比如x是string,那么就会报错:invalid type assertion: data.(string) (non-interface type string on left),当然也不能是常量,常量的类型已知,不需要做类型判断。T是类型字面量,就是类型的名称,举例来说:

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

}

所以,x.(T)的方式只能判断一层?这点还没有经过证实,等后面看了源码之后再确定吧

#### 2.类型获取

可以使用反射的方式获取变量的类型

reflect.TypeOf(x)

比如:

var str string = "hello"

fmt.Println(reflect.TypeOf(str))

输出:string

#### 3.类型判断

如果有一系列的数据要识别类型,可以用switch的类型判断语句,分类识别确认。还是以上面json格式的识别判断为例:

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)

}

}

}

注意:switch这句,vv := v.(type)只有在switch中才能使用,如果单独使用是会报错的。

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


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Advanced Web Metrics with Google Analytics

Advanced Web Metrics with Google Analytics

Brian Clifton / Sybex / 2008 / USD 39.99

Are you getting the most out of your website? Google insider and web metrics expert Brian Clifton reveals the information you need to get a true picture of your site's impact and stay competitive usin......一起来看看 《Advanced Web Metrics with Google Analytics》 这本书的介绍吧!

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具