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

use*_*501 23 interface map go

从一个来源我不能影响我在地图中给出数据,它到达时map[interface {}]interface {}.

我需要处理包含的数据,最好是map[string]string(内部的数据非常适合).

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

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

我怎样才能做fmt.Println能做的事情?

小智 17

处理未知接口的安全方法,只需使用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)
}
Run Code Online (Sandbox Code Playgroud)


Swo*_*gan 14

也许我误解了这个问题,但这会有用吗?

m := make(map[interface{}]interface{})
m["foo"] = "bar"

m2 := make(map[string]string)   

for key, value := range m {        
    switch key := key.(type) {
    case string:
        switch value := value.(type) {
        case string:
            m2[key] = value
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考,您可以在switch语句中进行分配,这样您就不必进行类型断言:http://play.golang.org/p/-ZeUXTKu9a (5认同)