【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

可以看出以下类型:

相关推荐
码农大叔的博客10 分钟前
golang示例:for九九乘法表
开发语言·算法·golang
圣殿骑士-Khtangc1 小时前
Go-sync-Pool对象池最佳实践与源码分析
golang
互联网中的一颗神经元1 小时前
01. Go 内存管理全景架构
java·jvm·golang
有脚就行1 小时前
第24篇-Go-gRPC推理服务-高性能跨语言通信
开发语言·人工智能·后端·golang
圣殿骑士-Khtangc14 小时前
Go-Mutex源码解析从自旋到饥饿模式的完整演进
golang
圣殿骑士-Khtangc1 天前
Go大厂面试真题精讲之并发安全Map的实现方案
golang
运维开发笔记1 天前
3.8 Go switch 语句学习笔记
golang
圣殿骑士-Khtangc1 天前
Go-Channel面试精讲从底层结构到select随机性
golang
北漂燕郊杨哥1 天前
dsh-desktop:DeepSeek Harness 的本地优先桌面应用
golang·wails·deepseek·deepseekharness
朋克洛德的码农2 天前
Go并发-sync包四剑客:Mutex、RWMutex、WaitGroup、Once-从入门到原理
开发语言·后端·golang