【golang interface】Golang中对interface{}做type assertion和type switch学习笔记

更新时间:2020-04-02    来源:安卓教程    手机版     字体:

【www.bbyears.com--安卓教程】

interface{}是一个通用类型,可以储存任意类型的值。如下方法来获取值的实际类型:
如果你比较确定类型可以使用type assertion:

var num interface{} = 100
if val,ok := num.(int); ok {
    fmt.Println(val)
}

如果你不确定interface{}的具体类型,使用type switch:

var str interface{} = "abc"
 
switch v := str.(type) {
case string:
 fmt.Println(v)
case int32, int64:
 fmt.Println(v)
default:
 fmt.Println("unknown")
}

本文来源:http://www.bbyears.com/shoujikaifa/91282.html

热门标签

更多>>

本类排行