doufan9805 2014-12-18 11:15
浏览 20
已采纳

如何从地图中获取价值

Problem

Fetching data from map

Data Format

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

Note

How to get the following value from the above result

1.Event_dtmReleaseDate

2.strID

3.Trans_strGuestList

What i tried:

  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)

  • 写回答

1条回答 默认 最新

  • doujiu6976 2014-12-18 11:22
    关注

    Your variable is a map[string]interface {} which means the key is a string but the value can be anything. In general the way to access this is:

    mvVar := myMap[key].(VariableType)
    

    Or in the case of a string value:

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

    Note that this will panic if the type is not correct or the key does not exist in the map, but I suggest you read more about Go maps and type assertions.

    Read about maps here: http://golang.org/doc/effective_go.html#maps

    And about type assertions and interface conversions here: http://golang.org/doc/effective_go.html#interface_conversions

    The safe way to do it without a chance to panic is something like this:

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了