英文:
What is the best way to convert array of interface into array of map in golang?
问题
我已经创建了一个Web服务器,该服务器能够接收POST请求。然而,当我在POST数据中发送map[string]string数组时,服务器将其接收为interface{}数组。我该如何将其转换回map[string]string数组?
例如:当我在POST请求中发送以下示例时,
params : [{"name" : "shail", "age" : 24}]
我将params发送为
[](map[string]string)
但是当服务器接收到这个数据时,它将params视为
[]interface{}
我该如何将params赋值给由
[](map[string]interface{})
定义的变量?
英文:
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
得分: 1
你可以对值进行类型断言来完成最简单的操作:
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"])
}
这段代码的作用是将一个map[string]string
类型的值存储到一个[]interface{}
类型的切片中,并通过类型断言将其取出并赋值给dest
变量。然后打印出dest
的类型和键值对中键为"hello"的值。
英文:
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"])
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论