go - 这个成语有名字吗?

标签 go idioms

这个成语有没有根据接口(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()]
}

复制自encoding/json并稍作改动以供演示。

最佳答案

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

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
}

关于go - 这个成语有名字吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42045034/

相关文章:

go - 错误检测,选择 channel

c++ - 对象构造函数 "settings"习语

python - 定义类属性的习惯用法

function - Clojure 函数的更惯用和优雅的方式

c# - 什么是惯用代码?

go - 如何处理客户端超时错误?

go - 在没有 oAuth 的情况下针对 Azure AD 验证用户凭据

python - 从 http POST 请求中解码 JSON

使用 init() 进行 Google 云函数 Golang 单元测试

rust - 将 1 元组结构转换为包含的元素的惯用方法是什么?