如何从地图中获取价值 - GOLang?

kar*_*ick 18 go

我在工作 __CODE__

问题

从地图中获取数据

数据格式

res = map[Event_dtmReleaseDate:2009-09-15 00:00:00 +0000 +00:00 Trans_strGuestList:<nil> strID:TSTB]
Run Code Online (Sandbox Code Playgroud)

注意

如何从上面的结果中获取以下值

1.Event_dtmReleaseDate

2.strID

3.Trans_strGuestList

我尝试了什么:

  1. res.Map( "Event_dtmReleaseDate");

错误:res.Map undefined(类型map [string] interface {}没有字段或方法Map)

  1. res.Event_dtmReleaseDate;

错误:v.id undefined(类型map [string] interface {}没有字段或方法id)

任何建议都将不胜感激

Not*_*fer 52

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

mvVar := myMap[key].(VariableType)
Run Code Online (Sandbox Code Playgroud)

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

id  := res["strID"].(string)
Run Code Online (Sandbox Code Playgroud)

请注意,如果类型不正确或地图中不存在键,这将会出现混乱,但我建议您阅读有关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
}
Run Code Online (Sandbox Code Playgroud)


Vla*_*pak 17

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

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)
}
Run Code Online (Sandbox Code Playgroud)

结果将是:

key exists in map: true, value: bar
Run Code Online (Sandbox Code Playgroud)