【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

可以看出以下类型:

相关推荐
geovindu13 小时前
go: Semaphore Pattern
开发语言·后端·设计模式·golang·企业级信号量模式
dusk_star16 小时前
go语言--笔记--封装、组合(继承)
笔记·golang
姚不倒18 小时前
Go 语言基础入门:从零到实战,一篇文章掌握核心语法
云原生·golang
XMYX-020 小时前
33 - Go 文本模板 template:从入门到原理深挖
golang·正则表达式
知彼解己1 天前
从后端角度理解 AI Agent:理论 + Go 实战(附 MCP 服务器实现)
java·golang·ai编程
云川之下1 天前
【go】建工程、初始化、module/package/import语法
golang·初始化
XMYX-01 天前
32 - Go 正则表达式:从匹配字符串到理解 RE2 引擎
golang·正则表达式
存在morning1 天前
【GO语言开发实践】二 GO 并发快速上手
大数据·开发语言·golang
geovindu2 天前
go: Read-Write Lock Pattern
开发语言·后端·设计模式·golang·读写锁模式
知彼解己2 天前
Go 开发环境 安装
后端·golang