Home  >  Article  >  Backend Development  >  How to get the value of interface{} in Go? (Interface conversion: interface{} is Resp, not mapinterface{})

How to get the value of interface{} in Go? (Interface conversion: interface{} is Resp, not mapinterface{})

WBOY
WBOYforward
2024-02-06 08:40:10857browse

Go中如何获取interface{}的值? (接口转换:interface{}是Resp,不是mapinterface{})

Question content

According to this question and the go code scanning queryrow to an existing map[string]interface{} in go, I am trying to get ## The keys and values ​​of #data["id"]

func login() func(c *lmhttp.context, code int, data interface{}) (int, interface{}) {
    return func(c *lmhttp.context, code int, data interface{}) (int, interface{}) {
    map_data := data.(map[string]interface{})
    fmt.print(map_data, map_data["id"])
  }
}

But I always encounter the following error, thank you very much for your suggestions.

interface conversion: interface {} is loginresp, not map[string]interface {}

I also pasted my

response code like this:

func (c *Context) Response(data interface{}) {
    c.result(http.StatusOK, data)
}


Correct answer


Finally, I get the value through the code below, use

marshal to get the json data, and then map and unmarshalit,

json_str, jsonErr := json.Marshal(data)
if json_str != nil {
    fmt.Printf("%v", jsonErr)
}
m := make(map[string]interface{})
err := json.Unmarshal([]byte(json_str), &m)
if err != nil {
    fmt.Println(err)
    fmt.Println("This is ID", m["id"])
}
        

The above is the detailed content of How to get the value of interface{} in Go? (Interface conversion: interface{} is Resp, not mapinterface{}). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete