简体   繁体   English

恐慌:接口转换:接口 {} 是字符串,而不是 float64

[英]panic: interface conversion: interface {} is string, not float64

I am trying to convert this simple python function to golang, but facing issues with this error我正在尝试将这个简单的 python function 转换为 golang,但遇到此错误的问题

panic: interface conversion: interface {} is string, not float64

python

def binance(crypto: str, currency: str):
    import requests

    base_url = "https://www.binance.com/api/v3/avgPrice?symbol={}{}"
    base_url = base_url.format(crypto, currency)
  
    try:
        result = requests.get(base_url).json()
        print(result)
        result = result.get("price")
    except Exception as e:
        
        return False
    return result

here is the golang version(longer code and more complicated code than should be)这是 golang 版本(比应该的更长的代码和更复杂的代码)

func Binance(crypto string, currency string) (float64, error) {
    req, err := http.NewRequest("GET", fmt.Sprintf("https://www.binance.com/api/v3/avgPrice?symbol=%s%s", crypto, currency), nil)
    if err != nil {
         fmt.Println("Error is req: ", err)
    }
    
    client := &http.Client{}
    
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("error in send req: ", err)
    }
    respBody, _ := ioutil.ReadAll(resp.Body)
    var respMap map[string]interface{}
    log.Printf("body=%v",respBody)
    json.Unmarshal(respBody,&respMap) 
    log.Printf("response=%v",respMap)
    price := respMap["price"]
    log.Printf("price=%v",price)

    pricer := price.(float64)
    return pricer, err
}

so what am I getting wrong here?那么我在这里做错了什么? Previously i had the error cannot use price (type interface {}) as type float64 in return argument: need type assertion and now i tried the type assertion with pricer:= price.(float64) and now this error以前我有错误cannot use price (type interface {}) as type float64 in return argument: need type assertion现在我尝试使用pricer:= price.(float64)进行类型断言,现在这个错误

panic: interface conversion: interface {} is string, not float64

It's telling you in the error, price is a string, not a float64, so you need to do (presumably):它在错误中告诉你, price是一个字符串,而不是一个 float64,所以你需要做(大概):

pricer := price.(string)
return strconv.ParseFloat(pricer, 64)

The error already tells you: price is a string.错误已经告诉你:价格是一个字符串。 So it is probably coming from a JSON that looks like:所以它可能来自 JSON,看起来像:

{
   "price": "123"
}

but not但不是

{
   "price": 123
}

The first unmarshals as string.第一个解组为字符串。 The second unmarshals as float64.第二个解组为 float64。

In your case, you have to parse it:在您的情况下,您必须解析它:

    price,err := strconv.ParseFloat(price.(string),64)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM