Home > Software engineering >  Golang gob serializes array wrongly
Golang gob serializes array wrongly

Time:12-15

I pass to gob array like this

[]int{}

but on the receiving end I get array like this

[]int(nil)

What is the differences between these arrays? Why gob serializes empty array like this?

CodePudding user response:

Why gob serializes empty array like this?

It's here in the docs: https://pkg.go.dev/encoding/gob

When a slice is decoded, if the existing slice has capacity the slice will be extended in place; if not, a new array is allocated.

From encoding/gob's point of view, []int{} and []int(nil) are not differentiable.

More info: https://github.com/golang/go/issues/10905

There is no general workaround, your code just has to deal with this in a specific way that depends on what you are trying to accomplish. If your goal is to make a deep copy, there are approaches that avoid gob entirely.

And it seems it's better to use a different solution

golang-nuts is probably a better place to discuss this. https://groups.google.com/forum/#!forum/golang-nuts

CodePudding user response:

[]int{} - empty slice

[]int(nil) - nil slice

Go Playground with example: https://go.dev/play/p/RQGa76vNI5G

More info about this gob behaviour you can find in this issue: https://github.com/golang/go/issues/10905

  • Related