9

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

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

panic: interface conversion: interface {} is json.Number, not float64
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
KuZon
  • 135
  • 1
  • 1
  • 6
  • 5
    `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. – mkopriva Jan 25 '18 at 13:02
  • 1
    Go doesn't support type casting at all. Only type conversion. – Jonathan Hall Jan 25 '18 at 13:42
  • @mkopriva - if it already has an underlying type why should he have to type assert at all? – Ken - Enough about Monica Apr 27 '19 at 23:21
  • 2
    @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. – mkopriva Apr 28 '19 at 05:16
  • @mkopriva - 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 interface – Ken - Enough about Monica Apr 28 '19 at 14:24
  • 2
    @horsehair panic's are runtime errors, not compile time errors. – mkopriva Apr 28 '19 at 14:26
  • @mkopriva - thank you. How does it know at runtime that this memory is occupied by a json.Number (not a float64)? – Ken - Enough about Monica Apr 28 '19 at 14:30
  • 2
    @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. – mkopriva Apr 28 '19 at 14:35
  • @mkopriva thanks again for all the great info. Have a great day – Ken - Enough about Monica Apr 28 '19 at 14:37

1 Answers1

19

Check this documentation to know the available methods on json.Number: https://golang.org/pkg/encoding/json/#Number

f, err := data.(json.Number).Float64()
Ilayaraja
  • 2,388
  • 1
  • 9
  • 9
  • 7
    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! – 0x574F4F54 Feb 20 '18 at 20:19