这个习语有一个名称吗?

huangapple go评论86阅读模式
英文:

Is there a name for this idiom?

问题

这种根据接口类型选择函数的习语有一个名称吗?

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()]
}

encoding/json 复制并稍作修改以进行演示。

英文:

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.

答案1

得分: 2

我会将其翻译为中文:

我将这称为动态方法派发。在Go语言接口实现中使用的机制与此相似,其中map[reflect.Type]encoderFunc被称为i-table。甚至可以只使用接口来重写编组(marshalling),只是我们不能为内置类型编写方法。

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
}
英文:

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
}

huangapple
  • 本文由 发表于 2017年2月5日 04:07:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/42045034.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定