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")
    }
相关推荐
anzhxu4 小时前
Go基础之环境搭建
开发语言·后端·golang
ILYT NCTR7 小时前
搭建Golang gRPC环境:protoc、protoc-gen-go 和 protoc-gen-go-grpc 工具安装教程
开发语言·后端·golang
叹一曲当时只道是寻常15 小时前
memos-cli 安装与使用教程:将 Memos 笔记同步到本地并支持 AI 语义搜索
人工智能·笔记·golang
geovindu16 小时前
go: Facade Pattern
设计模式·golang·外观模式
小众AI16 小时前
Go 多账户 WebDAV 服务实现
golang
念何架构之路17 小时前
图解defer
开发语言·后端·golang
我喜欢山,也喜欢海19 小时前
Java和go在并发上的表现为什么不一样
java·python·golang
geovindu20 小时前
go: Flyweight Pattern
开发语言·设计模式·golang·享元模式
不会写DN1 天前
Golang中的map的key可以是哪些类型?可以嵌套map吗?
后端·golang·go
止语Lab1 天前
Go vs Java GC:同一场延迟战争的两条路
java·开发语言·golang