How to get a value from map

后端 未结 2 715
闹比i
闹比i 2020-12-24 06:06

Problem

Fetching data from map

Data Format

res = map[Event_dtmReleaseDate:2009-09-15 00:00:00 +0000 +00:00 Trans_strGuestList: st         


        
相关标签:
2条回答
  • 2020-12-24 06:40

    In general to get value from map you have to do something like this:

    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)
    }
    

    Result will be:

    key exists in map: true, value: bar
    
    0 讨论(0)
  • 2020-12-24 06:41

    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
    }
    
    0 讨论(0)
提交回复
热议问题