Golang类型断言和类型转换
Golang大约 794 字示例
func main() {
var i interface{} = "hello"
s := i.(string)
fmt.Println(s) // hello
s, ok := i.(string)
fmt.Println(s, ok) // hello true
f, ok := i.(float64)
fmt.Println(f, ok) // 0 false
f = i.(float64) // panic 即使是字符串123也会panic 因为类型不同
fmt.Println(f)
}
类型转换
使用t := i.(T)
对已知interface{}
进行转换。
类型断言后转换
方式一
使用t, ok := i.(T)
对未知interface{}
进行断言,若ok
为true
,则t
赋值为转换后的值,若ok
为false
,则t
为类型对应的默认值(如:int
默认值是0
,string
默认值是""
)。
方式二
使用switch
来判断object.(type)
的类型并进行转换。
func Cast(object interface{}) {
switch object.(type) {
case string:
fmt.Println("string#", object.(string))
case int:
fmt.Println("int#", object.(int))
case float64:
fmt.Println("float64#", object.(float64))
// 其他类型
}
}
参考
阅读 33 · 发布于 2021-01-13
————        END        ————
扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看换一批
- MongoDB批量导入csv数据阅读 1394
- Linux之安装Maven阅读 342
- PHP序列化与反序列化阅读 386
- PostgreSQL使用\copy命令时报character with byte sequence 0xc3 0xa5 in encoding "UTF8" has no equivalent in encoding "GBK"阅读 3073
- Android禁止EditText弹出软件盘阅读 1106
- Elasticsearch使用filter和range过滤器搜索阅读 631
- gradle生成gradlew设置版本及属性阅读 1038
- 软考-系统架构设计师:规范化理论-价值与用途阅读 293
- OpenResty历险记阅读 648
- 23种设计模式阅读 345