go中使用空接口保存任意值的字典
package main
import (
"fmt"
)
// 空接口作为函数参数
func show(a interface{}) {
fmt.Printf("type:%T value:%v
", a, a)
}
func main() {
var studentInfo = make(map[string]interface{})
studentInfo["name"] = "abao"
studentInfo["age"] = "25"
studentInfo["married"] = false
fmt.Println(studentInfo)
}
go类型断言,提取空接口可以存储任意类型的值
func main() {
var x interface{}
x = "Hello World"
v, ok := x.(string) // v获取值,ok获取返回的状态
if ok {
fmt.Println(v)
} else {
fmt.Println("类型断言失败")
}
}
使用swith case
func justifyType(x interface{}) {
switch v := x.(type) {
case string:
fmt.Printf("x is a string,value is %v
", v)
case int:
fmt.Printf("x is a int is %v
", v)
case bool:
fmt.Printf("x is a bool is %v
", v)
default:
fmt.Println("unsupport type!")
}
}