[英]panic: interface conversion: interface {} is string, not float64
我正在尝试将这个简单的 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
这是 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
}
那么我在这里做错了什么? 以前我有错误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
它在错误中告诉你, price
是一个字符串,而不是一个 float64,所以你需要做(大概):
pricer := price.(string)
return strconv.ParseFloat(pricer, 64)
错误已经告诉你:价格是一个字符串。 所以它可能来自 JSON,看起来像:
{
"price": "123"
}
但不是
{
"price": 123
}
第一个解组为字符串。 第二个解组为 float64。
在您的情况下,您必须解析它:
price,err := strconv.ParseFloat(price.(string),64)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.