Created
March 21, 2025 00:11
-
-
Save gammazero/814bad38b4db29662a1894651c4505ac to your computer and use it in GitHub Desktop.
gob encode and decode pointers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func encodePointer(encoder *gob.Encoder, ptr any) error { | |
isNil := ptr == nil || (reflect.ValueOf(ptr).Kind() == reflect.Ptr && reflect.ValueOf(ptr).IsNil()) | |
if err := encoder.Encode(isNil); err != nil { | |
return err | |
} | |
if isNil { | |
return nil | |
} | |
return encoder.Encode(ptr) | |
} | |
func decodePointer(decoder *gob.Decoder, ptr any) error { | |
var isNil bool | |
err := decoder.Decode(&isNil) | |
if err != nil { | |
return err | |
} | |
if isNil { | |
return nil | |
} | |
return decoder.Decode(ptr) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment