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")
    }
相关推荐
o0o_-_1 天前
【go/gopls/mcp】官方gopls内置mcp server使用
开发语言·后端·golang
又菜又爱玩呜呜呜~2 天前
go使用反射获取http.Request参数到结构体
开发语言·http·golang
希望20172 天前
Golang | http/server & Gin框架简述
http·golang·gin
NG WING YIN3 天前
Golang關於信件的
开发语言·深度学习·golang
silver98863 天前
再谈golang的sql链接dsn
mysql·golang
刘媚-海外3 天前
Go语言开发AI应用
开发语言·人工智能·golang·go
deepwater_zone3 天前
Go语言核心技术
后端·golang
二哈不在线3 天前
代码随想录二刷之“动态规划”~GO
算法·golang·动态规划