英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论