How to decouple interface {} with interface {} in Go

There are several nodes in my system that communicate via RPC. I am trying to send the map interface [string] {} to another node via RPC. The sender uses json.Marshal and the receiver uses json.Unmarshal to receive the card. Say, on the sender side, the card contains [1] => 2, where 2 is of type uint32.
The problem is that Unmarshal is trying to find the underlying data type and converts 2 to float64 according to its default behavior, as stated here https://blog.golang.org/json-and-go . Later, casting float64 to uint32 causes a panic.

I referenced How to untie json in the {} interface in golang? . But for this we need to know the data type. In my case, the data can be of any type, so I want to save it as an interface {}. How can I decouple interface {} with interface {}?

+2
source share
1 answer

Unfortunately, the encoding/jsonpackage cannot be used because type information is not transmitted, and JSON numbers are not tied to the type value by default float64if there is no type information. You will need to define types struct, where you explicitly indicate that this field is of type uint32.

encoding/gob, . . :

m := map[string]interface{}{"1": uint32(1)}

b := &bytes.Buffer{}
gob.NewEncoder(b).Encode(m)

var m2 map[string]interface{}
gob.NewDecoder(b).Decode(&m2)
fmt.Printf("%T\n%#v\n", m2["1"], m2)

( Go Playground):

uint32
map[string]interface {}{"1":0x1}

gob , , JSON.

+3

Source: https://habr.com/ru/post/1663924/


All Articles