I am trying to handle dynamic interface type where I don't know whether interface is of type float64 or int64. I am using an API and Decode the response on a map where price is sometimes integer and sometimes float. eg JSON response is sometimes {price: 35} and sometimes {price: 35}
I have created an example code here
package main
import "fmt"
func main() {
response := make(map[string]interface{})
response["price"] = 2.1
response1 := make(map[string]interface{})
response1["price"] = 2
price_response, _ := response["price"].(float64)
price_response1, _ := response1["price"].(float64)
fmt.Println(price_response, "==> price_response") //output = 2.1
fmt.Println(price_response1,"==> price_response1") // //output = 0
}
The Output is get is
2.1 price_response
0 price_response1
Now here, I have to define type statically while doing type assertions on interface types. How am I supposed to handle this type issue to avoid getting 0 and instead getting the actual value converted into float64?
How am I supposed to handle this type issue to avoid getting 0 and instead getting the actual value converted into float64?
t, ok := i.(T)
This line of code checks whether the interface value i holds the concrete type T. If not, ok will be false and t will be the zero value of type T
price_response1, _ := response1["price"].(float64)
Here response1["price"] doesn't hold a type float64. Hence price_response1 has zero value of type float64, which is 0.
To print the underlying type of interface{} as a string you can use:
getType := fmt.Sprintf("%T", response1["price"])
fmt.Println(getType)
See the below code to get the actual value converted into float64, if the underlying type is int:
package main
import "fmt"
func convertToFloat64(resp interface{}) {
switch v := resp.(type) {
case int:
fmt.Println(float64(v), "==> price_response1")
case float64:
fmt.Println(v, "==> price_response")
default:
fmt.Println("unknown")
}
}
func main() {
response := make(map[string]interface{})
response["price"] = 2.1
convertToFloat64(response["price"])
response1 := make(map[string]interface{})
response1["price"] = 2
convertToFloat64(response1["price"])
}
Output:
2.1 ==> price_response
2 ==> price_response1
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.