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


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

    base_url = "{}{}"
    base_url = base_url.format(crypto, currency)
        result = requests.get(base_url).json()
        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("", 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{}
    price := respMap["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

>Solution :

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)

A better way would probably be to instead do

type response struct {
    Price float64 `json:",string"`
r := &response{}
respBody, _ := ioutil.ReadAll(resp.Body)
err := json.Unmarshal(respBody, r) 
return r.Price, err

The "string" option signals that a field is stored as JSON inside a JSON-encoded string. It applies only to fields of string, floating point, integer, or boolean types.

Leave a ReplyCancel reply