【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

可以看出以下类型:

相关推荐
Tony Bai1 小时前
【Go模块构建与依赖管理】09 企业级实践:私有仓库与私有 Proxy
开发语言·后端·golang
Lucky小小吴1 小时前
开源项目5——Go版本快速管理工具
开发语言·golang·开源
进化中的码农2 小时前
Go中的泛型编程和reflect(反射)
开发语言·笔记·golang
apocelipes4 小时前
POSIX兼容系统上read和write系统调用的行为总结
linux·c语言·c++·python·golang·linux编程
童话ing5 小时前
【Golang】常见数据结构原理剖析
数据结构·golang
Wzx19801214 小时前
go基础语法练习
开发语言·后端·golang
RedJACK~1 天前
Go Ebiten小游戏开发:扫雷
开发语言·后端·golang
研究司马懿1 天前
【ETCD】ETCD——confd配置管理
数据库·golang·自动化·运维开发·etcd·argocd·gitops
钢门狂鸭2 天前
go开发规范指引
开发语言·驱动开发·golang
脚踏实地的大梦想家2 天前
【Go】P19 Go语言并发编程核心(三):从 Channel 安全到互斥锁
开发语言·安全·golang