问题
从 map 中获取数据
数据格式
res = map[Event_dtmReleaseDate:2009-09-15 00:00:00 +0000 +00:00 Trans_strGuestList:<nil> strID:TSTB]
注意
如何从上面的结果中得到下面的值
Event_dtmReleaseDate
strID
Trans_strGuestList
我尝试了什么:
res.Map("Event_dtmReleaseDate");
Error : res.Map undefined (type map[string]interface {} has no field or method Map)
res.Event_dtmReleaseDate;
Error: v.id undefined (type map[string]interface {} has no field or method id)
最佳答案
您的变量是 map[string]interface {}
,这意味着键是字符串,但值可以是任何值。一般来说,访问它的方法是:
mvVar := myMap[key].(VariableType)
或者在字符串值的情况下:
id := res["strID"].(string)
请注意,如果类型不正确或映射中不存在键,则会出现 panic ,但我建议您阅读有关 Go 映射和类型断言的更多信息。
在此处阅读 map :http://golang.org/doc/effective_go.html#maps
关于类型断言和接口(interface)转换:http://golang.org/doc/effective_go.html#interface_conversions
没有机会 panic 的安全方法是这样的:
var id string
var ok bool
if x, found := res["strID"]; found {
if id, ok = x.(string); !ok {
//do whatever you want to handle errors - this means this wasn't a string
}
} else {
//handle error - the map didn't contain this key
}
关于go - 如何从 map 中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27545270/