在Go中如何将interface{}转换为其他类型? (接口转换:interface{}为Resp,非map[interface{}])

时间:2024-03-02

浏览:402

作者:佚名

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《在Go中如何将interface{}转换为其他类型? (接口转换:interface{}为Resp,非map[interface{}])》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

根据这个问题和go代码扫描queryrow到go中现有的map[string]interface{},我试图获取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"])
  }
}

但我总是遇到如下错误,非常感谢您的建议。

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

我还粘贴了我的 response 代码,如下所示:

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


正确答案


最后,我通过下面的代码获取值,使用marshal获取json数据,然后map和unmarshal它,

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

终于介绍完啦!小伙伴们,这篇关于《在Go中如何将interface{}转换为其他类型? (接口转换:interface{}为Resp,非map[interface{}])》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

本文内容来源于互联网,如有侵权请联系删除。

相关文章

更多

热门专题

更多
首页