Skip to content

proposal: encoding/gob: allow override type marshaling #36353

@dsnet

Description

@dsnet

This is the equivalent change to encoding/gob as what's proposed in #5901 for encoding/json.

I propose adding the following methods:

// RegisterFunc registers a custom encoder to use for specialized types.
// The input f must be a function of the type func(T) ([]byte, error).
//
// When marshaling a value of type R, the function f is called
// if R is identical to T for concrete types or
// if R implements T for interface types.
// Precedence is given to registered encoders that operate on concrete types,
// then registered encoders that operate on interface types
// in the order that they are registered, then the specialized marshal methods
// (i.e., GobEncode or MarshalBinary), and lastly the default behavior of Encode.
//
// It panics if T is already registered or if interface{} is assignable to T.
func (e *Encoder) RegisterFunc(f interface{})

// RegisterFunc registers a custom decoder to use for specialized types.
// The input f must be a function of the type func([]byte, T) error.
//
// When unmarshaling a value of type R, the function f is called
// if R is identical to T for concrete types or
// if R implements T for interface types.
// Precedence is given to registered decoders that operate on concrete types,
// then registered decoders that operate on interface types
// in the order that they are registered, then the specialized unmarshal methods
// (i.e., GobDecode or UnmarshalBinary), and lastly the default behavior of Decode.
//
// It panics if T is already registered or if interface{} is assignable to T.
func (d *Decoder) RegisterFunc(f interface{})

One such use case for this is to make encoding/gob compatible with higher-order Go types containing protobuf messages.

enc := gob.NewEncoder(w)
enc.RegisterFunc(proto.Marshal)
enc.Encode(v)

dec := gob.NewDecoder(r)
dec.RegisterFunc(proto.Unmarshal)
dec.Decode(v)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Incoming

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions