golang
的map
读取是不需要判断key是否存在的,不存在的key会返回默认值。
- 如果map的value是interface,那么interface是需要先进行类型转换的,非要求类型的转换,得到结果是
nil
。
package main
import "fmt"
var m map[string]interface{}
func getStr(k string) string {
v, ok := m[k].(string)
if ok {
return v
} else {
return "Null"
}
}
func getNum(k string) int {
v, ok := m[k].(int)
if ok {
return v
} else {
return 0
}
}
func getFunc(k string) string {
v, ok := m[k].(func(name string, age int) string)
if ok {
return v(getStr("name"), getNum("age"))
} else {
return "unknow"
}
//v, _ := m[k].(func(name string, age int) string)
//return v("a", 12)
}
func main() {
fmt.Println("Hello, 世界")
m = map[string]interface{}{
"name": "zhangsan",
"age": 12,
"is_female": false,
"hi": func(name string, age int) string {
return fmt.Sprintf("hello, my name is %s, i'm %d year old.", name, age)
},
}
fmt.Println(getStr("name"))
fmt.Println(getStr("age"))
fmt.Println(getStr("hi"))
fmt.Println(getNum("age"))
fmt.Println(getFunc("age"))
fmt.Println(getFunc("sayhi"))
fmt.Println(getFunc("hi"))
}