Is there a name for this idiom where a function is chosen based on type of interface ?
type encoderFunc func(e *encodeState, v reflect.Value, opts encOpts)
var encoderCache struct {
m map[reflect.Type]encoderFunc
}
func (e *encodeState) marshal(v interface{}, opts encOpts) (err error) {
v := refect.ValueOf(v)
valueEncoder(v)(e, v, opts)
return nil
}
func valueEncoder(v reflect.Value) encoderFunc {
return encoderCache.m[v.Type()]
}
Copied from encoding/json and slightly altered for demonstration.
I'd call this dynamic method dispatch. More or less the same mechanism used in Go interface implementation where map[reflect.Type]encoderFunc
called i-table. One even can rewrite marshalling just with interfaces, except we can't write methods for builtin types.
type encodable interface{
encode(e *encodeState, opts encOpts)
}
func (st SomeType) encode(e *encodeState, opts encOpts){
...
}
...
func (ot OtherType) encode(e *encodeState, opts encOpts){
...
}
func (e *encodeState) marshal(v encodable, opts encOpts) (err error) {
v.encode(e, opts)
return nil
}