Convert Json.Number into int/int64/float64 in Go
Asked Answered
I

1

10

I have a variable, data, which is an interface. When I print its type, I get it as json.Number. How do I typecast to int/int64/float64?

If I try data.(float64), it ends up with a panic error:

panic: interface conversion: interface {} is json.Number, not float64

Inobservance answered 25/1, 2018 at 12:59 Comment(9)
data.(json.Number).Int64() You type assert to the actual underlying type, not to an arbitrary type you wish it was. That means that if an interface's underlying type is json.Number you type assert it as json.Number. And also v.(T) in Go is not conversion but type assertion.Opponent
Go doesn't support type casting at all. Only type conversion.Marcellamarcelle
@Opponent - if it already has an underlying type why should he have to type assert at all?Pray
@horsehair because Go doesn't know the underlying type at compile type and type assertion is a test that helps you figure out the underlying type of an interface value at runtime. This is useful if you need to use the "features" of the underlying type as opposed to the "features" of the interface type.Opponent
@Opponent - makes sense. But, why can't one do data.(string) (or any arbitrary data type), in that case? Why wouldn't the compiler just grab the bytes at the appropriate addresses and convert them? At compile time instead one gets the error Kuzon (questioner) did - so the compiler does seem to know what data type resides at (in?) that interfacePray
@horsehair panic's are runtime errors, not compile time errors.Opponent
@Opponent - thank you. How does it know at runtime that this memory is occupied by a json.Number (not a float64)?Pray
@horsehair type information is stored in Go's runtime system. Also while json.Number's underlying type may be string the two types are not the same and so type-asserting one to the other is bound to fail, however converting one to the other is ok.Opponent
@Opponent thanks again for all the great info. Have a great dayPray
L
20

Check the documentation for type Number to know the available methods on json.Number:

f, err := data.(json.Number).Float64()
Lubricous answered 25/1, 2018 at 14:3 Comment(1)
As a newcomer to go, an example like this is exactly what I needed. While the documentation referenced is accurate, it lacks a straight-forward demonstration of how to use the functionality. Thanks!Conservancy

© 2022 - 2024 — McMap. All rights reserved.