简体   繁体   中英

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

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)

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

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):

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:

{
   "price": "123"
}

but not

{
   "price": 123
}

The first unmarshals as string. The second unmarshals as float64.

In your case, you have to parse it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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