簡體   English   中英

如何處理 Golang 中的動態接口類型?

[英]How to handle dynamic interface types in Golang?

我正在嘗試處理我不知道接口是 float64 還是 int64 類型的動態接口類型。 我正在使用 API 並解碼 map 上的響應,其中價格有時是 integer 有時是浮動的。 例如 JSON 響應有時是 {price: 35} 有時是 {price: 35}

我在這里創建了一個示例代碼

package main
import "fmt"

func main() {

    response := make(map[string]interface{})
    response["price"] = 2.1

    response1 := make(map[string]interface{})
    response1["price"] = 2

    price_response, _ := response["price"].(float64)
    price_response1, _ := response1["price"].(float64)

    fmt.Println(price_response, "==> price_response") //output = 2.1
    fmt.Println(price_response1,"==> price_response1") // //output = 0
}

Output 得到的是

2.1 price_response
0 price_response1

現在在這里,我必須在對接口類型進行類型斷言時靜態定義類型。 我應該如何處理這種類型的問題以避免得到 0 而是將實際值轉換為 float64?

我應該如何處理這種類型的問題以避免得到 0 而是將實際值轉換為 float64?

t, ok := i.(T)

這行代碼檢查接口值 i 是否持有具體類型 T。如果沒有,ok 將為 false,t 將是類型 T 的零值

price_response1, _ := response1["price"].(float64)

這里 response1["price"] 不包含 float64 類型。 因此 price_response1 的 float64 類型的值為零,即 0。

要將 interface{} 的底層類型打印為字符串,您可以使用:

getType := fmt.Sprintf("%T", response1["price"])
fmt.Println(getType) 

如果底層類型是 int,請參見下面的代碼以獲取轉換為 float64 的實際值:

package main

import "fmt"

func convertToFloat64(resp interface{}) {
    switch v := resp.(type) {
    case int:
        fmt.Println(float64(v), "==> price_response1")

    case float64:
        fmt.Println(v, "==> price_response")
    default:
        fmt.Println("unknown")
    }
}

func main() {
    response := make(map[string]interface{})
    response["price"] = 2.1
    convertToFloat64(response["price"])
    response1 := make(map[string]interface{})
    response1["price"] = 2
    convertToFloat64(response1["price"])

}

Output:

2.1 ==> price_response
2 ==> price_response1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM