How to get value from a map - GOLang?

I work at GOLANG

Problem

Receive data from the card

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:

  • res.Map ("Event_dtmReleaseDate");

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

  1. res.Event_dtmReleaseDate;

Error: v.id undefined (type map [string] interface {} does not have a field or method identifier)

Any suggestion would be appreciated.

+6
source share
1 answer

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

 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 incorrect or the key does not exist on the map, but I suggest you learn more about Go maps and claim types.

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

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

A safe way to do this without the possibility of panic is 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 } 
+23
source

Source: https://habr.com/ru/post/979847/


All Articles