Go 数据类型判断

1、使用Go的空接口:
i.(type) 只能在switch中使用,函数没有返回值

func m_type(i interface{}) {
    switch i.(type) {
    case string:
        //...
    case int:
        //...
    }
    return
}

2、使用反射:
reflect.TypeOf(x)

package main

import (
    "fmt"
    "reflect"
)

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

总结:第一种方法需要先知道有几种类型,第二种可以对任意对象使用。

猜你喜欢

转载自blog.csdn.net/tovids/article/details/77880789