go语言获取变量类型的4种方式

在go语言中我们常常需要获取某个变量的类型,其他语言如python可以使用 type(x), javascript中可以使用 typeof x 获取变量类型, Go 语言中我们也可以通过一下4种方式获取变量的类型。

  1. 通过 fmt.Printf 的 %T 打印变量的类型;
Go 复制代码
var x float64 = 3.4
fmt.Printf("Type of x: %T\n", x)
  1. 通过反射获取类型 reflect.Typeof(变量) 、 reflect.ValueOf(变量).Kind() ;
Go 复制代码
var x float64 = 3.4
fmt.Println("Type of x:", reflect.TypeOf(x)) // float64

// ValueOf 获取数据类型
fmt.Printf("%s \n", reflect.ValueOf(x).Kind()) // float64
  1. 类型断言检测变量类型
Go 复制代码
   var i interface{} = "Hello"
    // 类型断言
    s, ok := i.(string)
    if ok {
        fmt.Println(s) 
    }
  1. 类型选择, 与类型推断类似,也是类型检查和转换的一种方式。
Go 复制代码
    var i interface{} = "Hello"

    // 类型选择
    switch v := i.(type) {
    case string:
        fmt.Println(v) // 
    case int:
        fmt.Println(v * 2)
    default:
        fmt.Println("Unknown type")
    }
相关推荐
ruxingli14 小时前
Golang iota详解
开发语言·后端·golang
暗冰ཏོ16 小时前
Go 语言从入门到后端项目实战完整指南
开发语言·后端·golang·go·go语言
Reisentyan17 小时前
[Advance]GoLang Learn Data Day 4
java·数据库·golang
brycegao32117 小时前
Vue3+Go 全栈项目上线阿里云|从 0 到 1 踩坑全纪录
开发语言·阿里云·golang
会编程的土豆18 小时前
Go 里的 error 接口 + 假 nil(超级重点)
开发语言·后端·golang
basketball61619 小时前
Golang:基本输入输出使用方法总结
开发语言·golang·xcode
codeejun20 小时前
每日一Go-70、Prometheus + Grafana 从采集到告警的完整实战(Go + Kind)
golang·grafana·prometheus
会编程的土豆20 小时前
Go 里 interface 为什么能比较?到底在比什么?
开发语言·后端·golang
GDAL20 小时前
在 Windows 上做 Go 跨平台编
windows·golang
basketball61620 小时前
Golang:基础语法总结
开发语言·后端·golang