【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

可以看出以下类型:

相关推荐
Nejosi_念旧10 小时前
解读 Go 中的 constraints包
后端·golang·go
风无雨10 小时前
GO 启动 简单服务
开发语言·后端·golang
小明的小名叫小明10 小时前
Go从入门到精通(19)-协程(goroutine)与通道(channel)
后端·golang
光影少年10 小时前
从前端转go开发的学习路线
前端·学习·golang
斯普信专业组10 小时前
Go语言包管理完全指南:从基础到最佳实践
开发语言·后端·golang
高hongyuan19 小时前
Go语言教程-占位符及演示代码
开发语言·后端·golang
风无雨1 天前
GO启动一个视频下载接口 前端可以边下边放
前端·golang·音视频
LuckyLay2 天前
使用 Docker 搭建 Go Web 应用开发环境——AI教你学Docker
前端·docker·golang
{⌐■_■}2 天前
【软件工程】tob和toc含义理解
前端·数据库·mysql·golang·软件工程·tidb
hackchen3 天前
Go与JS无缝协作:Goja引擎实战之错误处理最佳实践
开发语言·javascript·golang