【go语言基础】go类型断言 type switch + case,t := x.(type)

有这么一个场景,当你在和用户对接的时候,调取第三方接口,但是第三方接口的时常变化的,比如从string类型变为int,这个时候你需要再去判断类型,获取第三方接口的参数。比较麻烦。

针对这一场景,go中对switch进行了升级。a是一个未知类型的变量,switch b := a.(type) 用这个方式来赋值,b + case进行判断就是有确定类型的变量。

未知类型比如类似于java的Object,interface{},通过case之后,变成确定的数据类型的值。

先看下例子:

a是任意类型,因为传入值的类型是不确定的。所以我们赋值a为任意类型。

case是需要的类型,如果需要的是string类型,那么将string类型给b,如果需要int类型,那么将int类型给b,其实b拥有a的类型,需要什么类型,那么就case什么类型。

Go 复制代码
func test() {
    
    // a是任意类型,这个可以当做传入的参数,根据传入的参数来进行判断。
	var a any
	switch b := a.(type) {
	case string:
		fmt.Printf("type of b is %T\n", b)
		fmt.Printf("value of b is %v\n", b)
	case int:
		fmt.Printf("type of b is %T\n", b)
		fmt.Printf("value of b is %v\n", b)
	default:
		fmt.Printf("type of b is %T\n", b)
		fmt.Printf("value of b is %v\n", b)
	}
}
Go 复制代码
func test() {
	var a any = 1
	switch b := a.(type) {
	case string:
		fmt.Printf("type of b is %T\n", b)
		fmt.Printf("value of b is %v\n", b)
	case int:
		fmt.Printf("type of b is %T\n", b)
		fmt.Printf("value of b is %v\n", b)
	default:
		fmt.Printf("type of b is %T\n", b)
		fmt.Printf("value of b is %v\n", b)
	}
}

结果为:

Go 复制代码
type of b is int
value of b is 1

可以看出以下类型:

相关推荐
源代码•宸18 小时前
Golang原理剖析(channel面试与分析)
开发语言·经验分享·后端·面试·golang·select·channel
moxiaoran575320 小时前
Go语言中的泛型
golang
加油201920 小时前
GO语言内存逃逸和GC机制
golang·内存管理·gc·内存逃逸
源代码•宸20 小时前
Golang原理剖析(channel源码分析)
开发语言·后端·golang·select·channel·hchan·sudog
liuyunshengsir20 小时前
golang Gin 框架下的大数据量 CSV 流式下载
开发语言·golang·gin
CHHC188020 小时前
golang 项目依赖备份
开发语言·后端·golang
老蒋每日coding20 小时前
AI智能体设计模式系列(八)—— 记忆管理模式
人工智能·设计模式·golang
且去填词2 天前
深入理解 GMP 模型:Go 高并发的基石
开发语言·后端·学习·算法·面试·golang·go
a程序小傲2 天前
京东Java面试被问:多活数据中心的流量调度和数据同步
java·开发语言·面试·职场和发展·golang·边缘计算
卜锦元2 天前
EchoChat搭建自己的音视频会议系统01-准备工作
c++·golang·uni-app·node.js·音视频