Go:地图的类型断言

rod*_*ece 5 dictionary go assertion

我正在从 JSON 读取数据结构。有一些转换正在进行,最后我有一个struct字段是 type 的地方interface{}。它实际上是一张地图,所以 JSON 将它放在一个map[string]inteface{}.

我实际上知道底层结构是map[string]float64并且我想这样使用它,所以我尝试做一个断言。以下代码重现了该行为:

type T interface{}

func jsonMap() T {
    result := map[string]interface{}{
        "test": 1.2,
    }
    return T(result)
}

func main() {
    res := jsonMap()

    myMap := res.(map[string]float64)

    fmt.Println(myMap)
}
Run Code Online (Sandbox Code Playgroud)

我收到错误:

panic: interface conversion: main.T is map[string]interface {}, not map[string]float64
Run Code Online (Sandbox Code Playgroud)

我可以执行以下操作:

func main() {
    // A first assertion
    res := jsonMap().(map[string]interface{})

    myMap := map[string]float64{
        "test": res["test"].(float64), // A second assertion
    }

    fmt.Println(myMap)
}
Run Code Online (Sandbox Code Playgroud)

这工作正常,但我发现它非常难看,因为我需要重建整个地图并使用两个断言。有没有正确的方法来强制第一个断言放弃interface{}并使用float64?换句话说,做原始断言的正确方法是什么.(map[string]float64)

编辑:

我正在解析的实际数据如下所示:

[
 {"Type":"pos",
 "Content":{"x":0.5 , y: 0.3}} ,

{"Type":"vel",
"Content":{"vx": 0.1, "vy": -0.2}}
]
Run Code Online (Sandbox Code Playgroud)

在 Go 中,我使用 astructencoding/json以下方式。

type data struct {
    Type string
    Content interface{}
}

// I read the JSON from a WebSocket connection
_, event, _ := c.ws.ReadMessage()

j := make([]data,0)
json.Unmarshal(event, &j)
Run Code Online (Sandbox Code Playgroud)

s7a*_*ley 6

不能键入断言map[string]interface{}map[string]float64。您需要手动创建新地图。

package main

import (
    "encoding/json"
    "fmt"
)

var exampleResponseData = `{
        "Data":[
            {
                "Type":"pos",
                "Content":{
                    "x":0.5,
                    "y":0.3
                }
            },
            {
                "Type":"vel",
                "Content":{
                    "vx":0.1,
                    "vy":-0.2
                }
            }
        ]
    }`

type response struct {
    Data []struct {
        Type    string
        Content interface{}
    }
}

func main() {
    var response response
    err := json.Unmarshal([]byte(exampleResponseData), &response)
    if err != nil {
        fmt.Println("Cannot process not valid json")
    }

    for i := 0; i < len(response.Data); i++ {
        response.Data[i].Content = convertMap(response.Data[i].Content)
    }
}

func convertMap(originalMap interface{}) map[string]float64 {
    convertedMap := map[string]float64{}
    for key, value := range originalMap.(map[string]interface{}) {
        convertedMap[key] = value.(float64)
    }

    return convertedMap
}
Run Code Online (Sandbox Code Playgroud)

你确定你不能定义Contentmap[string]float64?请参阅下面的示例。如果没有,你怎么知道你可以首先投射它?

type response struct {
    Data []struct {
        Type    string
        Content map[string]float64
    }
}

var response response
err := json.Unmarshal([]byte(exampleResponseData), &response)
Run Code Online (Sandbox Code Playgroud)