dictionary - Go: map 的类型断言

标签 dictionary go assertion

我正在从 JSON 中读取数据结构。进行了一些转换,最后我得到了一个 struct,其中一个字段的类型为 interface{}。它实际上是一张 map ,因此 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)
}

我得到错误:

panic: interface conversion: main.T is map[string]interface {}, not map[string]float64

我可以做以下事情:

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

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

    fmt.Println(myMap)
}

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

编辑:

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

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

{"Type":"vel",
"Content":{"vx": 0.1, "vy": -0.2}}
]

在 Go 中,我按以下方式使用 structencoding/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)

最佳答案

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

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
}

您确定不能将 Content 定义为 map[string]float64 吗?请参见下面的示例。如果没有,你怎么知道你可以在第一时间施放它?

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

var response response
err := json.Unmarshal([]byte(exampleResponseData), &response)

关于dictionary - Go: map 的类型断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35706501/

相关文章:

java - 实现多线程访问的java映射,每个键只更新一次

orm - 无法使用Beego的ORM .All()

c++ - OpenCV 相机校准,断言失败 <ni> 0 && ni==ni1>

python - 尝试将 dict 写入文件时出现 KeyError [Python]

java - 如何在 JasperReport 中使用 java Hashmap 作为变量

go - 在同一个共享 channel 上并发选择

date - 仅比较日期部分时间。Golang 中的时间

c++ - boost::shared_ptr 断言错误与 boost::asio:io_service

assertion - CUDA:如何在内核代码中断言?

键的Python循环索引,使用items()时的值for-loop