【问题标题】:How to get a value from map如何从地图中获取值
【发布时间】:2014-12-18 11:15:14
【问题描述】:

问题

从地图中获取数据

数据格式

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");

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

  1. res.Event_dtmReleaseDate;

错误:v.id undefined (type map[string]interface {} has no field or method id)

【问题讨论】:

  • 地图是否正确初始化?因为您的数据格式不是正确的 go 语法。如果地图是map[string]something,您可以使用val := res["Event_dtmReleaseDate"]访问元素

标签: go


【解决方案1】:

您的变量是map[string]interface {},这意味着键是字符串,但值可以是任何值。一般来说,访问它的方法是:

mvVar := myMap[key].(VariableType)

或者在字符串值的情况下:

id  := res["strID"].(string)

请注意,如果类型不正确或映射中不存在键,则会出现恐慌,但我建议您阅读有关 Go 映射和类型断言的更多信息。

在此处阅读地图:http://golang.org/doc/effective_go.html#maps

关于类型断言和接口转换在这里:http://golang.org/doc/effective_go.html#interface_conversions

没有机会恐慌的安全方法是这样的:

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
}

【讨论】:

    【解决方案2】:

    一般来说,要从地图中获取价值,您必须执行以下操作:

    package main
    
    import "fmt"
    
    func main() {
        m := map[string]string{"foo": "bar"}
        value, exists := m["foo"]
        // In case when key is not present in map variable exists will be false.
        fmt.Printf("key exists in map: %t, value: %v \n", exists, value)
    }
    

    结果将是:

    key exists in map: true, value: bar
    

    【讨论】:

      猜你喜欢
      • 2012-05-28
      • 2019-05-21
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 2016-04-04
      相关资源
      最近更新 更多