go - 如何从 map 中获取值

标签 go

问题

从 map 中获取数据

数据格式

res = map[Event_dtmReleaseDate:2009-09-15 00:00:00 +0000 +00:00 Trans_strGuestList:<nil> strID:TSTB]

注意

如何从上面的结果中得到下面的值

  1. Event_dtmReleaseDate
  2. strID
  3. Trans_strGuestList

我尝试了什么:

  1. res.Map("Event_dtmReleaseDate");

Error : res.Map undefined (type map[string]interface {} has no field or method Map)

  1. 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/

相关文章:

go - 在磁盘上存储时间序列数据的滑动窗口

mongodb - 与 Golang/Mongodb 聚合出现错误 "Missing type in composite literal"

ajax - 使用 polymer core-ajax 向 golang 服务器发布请求?

go - Golang的draw2d包中填充一个像素

go - 在 go 中轮询函数直到 ok != true 的惯用方式

types - 不能在函数参数中使用 document[0](类型 uint8)作为类型 []byte

go - mgo.v2, $sample 总是返回 1 条相同的记录

go - Go 中的单向 channel 有什么意义?

go - 有人在 go-executable 上有简单的 pprof 使用吗?

sockets - golang unix 套接字错误。调用 : resource temporarily unavailable