从我无法影响的来源获得 map 中的数据,该数据以 map[interface {}]interface {}
的形式到达。
我需要处理包含的数据,最好是 map[string]string
(里面的数据非常适合)。
我还需要从数据中生成一个键列表,因为这些是事先不知道的。
我在网上找到的大多数类似问题或多或少都说这是不可能的,但如果我的 map 是 m
,fmt.Println(m)
会显示数据在那里,可读为 map[k0:v0 K1:v1 k2:v2 ... ]
。
我该如何做 fmt.Println 能够做的事情?
最佳答案
处理未知接口(interface)的安全方法,只需使用 fmt.Sprintf()
https://play.golang.org/p/gOiyD4KpQGz
package main
import (
"fmt"
)
func main() {
mapInterface := make(map[interface{}]interface{})
mapString := make(map[string]string)
mapInterface["k1"] = 1
mapInterface[3] = "hello"
mapInterface["world"] = 1.05
for key, value := range mapInterface {
strKey := fmt.Sprintf("%v", key)
strValue := fmt.Sprintf("%v", value)
mapString[strKey] = strValue
}
fmt.Printf("%#v", mapString)
}
关于map - 将 map[interface {}]interface {} 转换为 map[string]string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26975880/