【问题标题】:Is there a name for this idiom?这个成语有名字吗?
【发布时间】:2017-02-04 20:07:23
【问题描述】:

这个习语有名字吗?根据接口类型选择函数?

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 复制并稍作改动以进行演示。

【问题讨论】:

  • 我不知道 Go,但这让我觉得是一种继承。如果函数是 ABC 而不是接口的一部分,则该语言会根据其类型自动选择正确的方法。
  • @Carcigenicate,你指的是哪个功能?我认为这与继承无关。涉及的类型完全不相关。
  • Nvm,我想我看错了代码。从顶部的描述和代码来看,您似乎是在根据对象的类型分派一个函数。
  • 一个函数确实是根据对象的类型“分派”的,但这些类型彼此完全无关。通过继承(可能是多态),被调用的函数取决于对象的类型——但对象都是特定的父类型。

标签: go idioms


【解决方案1】:

我称之为动态方法调度。或多或少与 Go 接口实现中使用的机制相同,其中 map[reflect.Type]encoderFunc 调用 i-table。甚至可以仅使用接口重写编组,但我们不能为内置类型编写方法。

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
}

【讨论】:

    猜你喜欢
    • 2010-11-30
    • 1970-01-01
    • 2014-10-09
    • 2017-07-03
    • 2011-07-27
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    相关资源
    最近更新 更多