Go3

goalng type judge

This project is maintained by wangfakang

Go语言中怎样判断数据类型

要判断数据类型,可以用Go的空接口:
建一个函数t 设置参数i 的类型为空接口,空接口可以接受任何数据类型

方法一:

func type_judge(i interface{}) {    //函数type_judge 有一个参数i 
    switch i.(type) {      //多选语句switch
    case string:
        print("type is string")
    case int:
        print("type is int")
    }
    return
}

i.(type) 只能在switch中使用

方法二:

还可以用反射:

package main

import (
        "fmt"
        "reflect"
)

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

这样就可以得出变量x的类型信息,与上面不同的是:上面的方法要先知到它是几个类型中的一个,而这个方法可以对 任意对象使用.

欢迎一起交流学习  

在使用中有任何问题,欢迎反馈给我,可以用以下联系方式跟我交流

Thx

Author