dongyu1918 2015-08-29 22:14
浏览 4069

在golang中将接口数组转换为map数组的最佳方法是什么?

I've created a web server and this server is able to get POST request. However, when I send array of map[string]string in POST data, server receives it as array of interface{}. How can I convert it back to array of map[string]string?

Example : Like when I send following example in POST request,

params : [{"name" : "shail", "age" : 24}]

I'm sending params as

[](map[string]string)

but when server receives this data, it treats params as

[]interface{}

.How do I assign params in a variable defined by

[](map[string]interface{})

?

  • 写回答

1条回答 默认 最新

  • duanguochong0397 2015-08-29 22:24
    关注

    The easiest thing you can do is a type assertion on the values:

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    func main() {
        var source []interface{}
        var test = make(map[string]string, 0)
        test["hello"] = "World"
        source = append(source, test)
        var dest = source[0].(map[string]string)
        fmt.Println(reflect.TypeOf(dest).Kind())
        fmt.Println(dest["hello"])
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失