I am using the gob encoder/decoder to serialize and deserialize the strut into a byte array. I ran into an issue when big.Rat embedded into another struct. I am able to successfully encode and decodebig.Rat type directly without any issue. But big.Rat is embedded into another strut then I am able to encode successfully but during the decoding process, it throws panic: runtime error: invalid memory address or nil pointer dereference.
BTW, to solve this issue, I added implemented the GobEncoder/GobDecoder for the custom strut.
I am not sure the correct behavior here. How is the custom GobDecode implementation on big.Int, big.Rat, big.Float supposed to handle decoding into a nil pointer? The documentation for the GobDecoder interface doesn't specify anything about requiring the pointer to be non-nil, so it seems like implementations should handle that case by allocating a new instance.
For the code above, you can avoid the custom GobEncode/Decode workaround for now by initializing the embedded pointer:
@bmkessler the example was simplified for clarity (I work with @skuppa). In our actual use case, the big.Rat was nested several levels deep inside a more complicated struct necessitating the override of GobDecode.
Given that all the other structs were initialized until we got to the big.Rat, it certainly seems like it should allocate it. Additionally, the big.Rat.GobDecode does initialize the zero value if the length of the buffer is zero: https://golang.org/src/math/big/ratmarsh.go?s=1058:1099#L32
Yeah, this looks to be a general issue with the gob decode handling anonymous pointer fields that implement the GobDecoder interface. I made a simple reproducer for a custom type that properly initializes the struct if either the pointer field is not anonymous or if the struct doesn't implement the GobDecoder interface.
I think the issue title should be updated to something like encoding/gob: decoding fails for structs with anonymous pointer fields that implement GobDecoder interface as the issue is not specific to big.Rat