【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

可以看出以下类型:

相关推荐
2501_941982058 小时前
深度对比:Java、Go、Python 实现企微外部群推送,哪个效率更高?
java·golang·企业微信
参.商.14 小时前
【Day 27】121.买卖股票的最佳时机 122.买卖股票的最佳时机II
leetcode·golang
牛奔14 小时前
如何理解 Go 的调度模型,以及 G / M / P 各自的职责
开发语言·后端·golang
牛奔16 小时前
Go 是如何做抢占式调度的?
开发语言·后端·golang
清云随笔18 小时前
Golang基础
golang
牛奔21 小时前
Go 如何避免频繁抢占?
开发语言·后端·golang
不老刘1 天前
LiveKit 本地部署全流程指南(含 HTTPS/WSS)
golang·实时音视频·livekit
Tony Bai1 天前
再见,丑陋的 container/heap!Go 泛型堆 heap/v2 提案解析
开发语言·后端·golang
念何架构之路1 天前
Go进阶之panic
开发语言·后端·golang
先跑起来再说1 天前
Git 入门到实战:一篇搞懂安装、命令、远程仓库与 IDEA 集成
ide·git·后端·elasticsearch·golang·intellij-idea