So I am receiving an interface{}, but I want to in any way possible convert it to a float64 or return an error if not possible.
Here's what I'm doing:
func getFloat(unk interface{}) (float64, error) {
if v_flt, ok := unk.(float64); ok {
return v_flt, nil
} else if v_int, ok := unk.(int); ok {
return float64(v_int), nil
} else if v_int, ok := unk.(int16); ok {
return float64(v_int), nil
} else ... // other integer types
} else if v_str, ok := unk.(string); ok {
v_flt, err := strconv.ParseFloat(v_str, 64)
if err == nil {
return v_flt, nil
}
return math.NaN(), err
} else if unk == nil {
return math.NaN(), errors.New("getFloat: unknown value is nil")
} else {
return math.NaN(), errors.New("getFloat: unknown value is of incompatible type")
}
}
But I feel like I'm going about it the wrong way, is there a better way to do this?