小编典典

将map [interface {}] interface {}转换为map [string] string

go

从来源来看,我无法影响我在地图中获得的数据,该地图以表示map[interface {}]interface {}

我需要处理所包含的数据,最好是map[string]string(其中的数据非常适合该处理)。

我还需要从数据中生成键列表,因为这些键是事先未知的。

我可以在网上找到的大多数类似问题或多或少都说这是不可能的,但是如果我的地图是m,则fmt.Println(m)表明数据在那里,可读性为map[k0:v0 K1:v1 k2:v2 ... ]

我该怎么办fmt.Println可以做什么?


阅读 830

收藏
2020-07-02

共1个答案

小编典典

处理未知接口的一种安全方法,只需使用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)
}
2020-07-02