亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Go:地圖的類型斷言

Go:地圖的類型斷言

Go
料青山看我應如是 2021-12-20 10:39:49
我正在從 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)}我收到錯誤: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)}這工作正常,但我發現它非常難看,因為我需要重建整個地圖并使用兩個斷言。有沒有正確的方法來強制第一個斷言放棄interface{}并使用float64?換句話說,做原始斷言的正確方法是什么.(map[string]float64)?
查看完整描述

1 回答

?
瀟湘沐

TA貢獻1816條經驗 獲得超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

}

你確定你不能定義Content為 map[string]float64?請參閱下面的示例。如果沒有,你怎么知道你可以首先投射它?


type response struct {

    Data []struct {

        Type    string

        Content map[string]float64

    }

}


var response response

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


查看完整回答
反對 回復 2021-12-20
  • 1 回答
  • 0 關注
  • 202 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號