我需要做这样的事情:
// I have an interface with these two methods defined
type mapper interface {
ReadMapper(interface{}) interface{}
WriteMapper(interface{}) interface{}
}
那么我需要分配
ReadMapper
和 WriteMapper
在项目的其他地方定义的一些功能。有没有办法在 Go 中做这样的事情?给他们分配职能? V1Mapper mapper
V1Mapper.ReadMapper = functions()....
V1Mapper.WriteMapper = functions()....
然后,我需要另一个映射,并希望映射器作为值类型,并希望执行如下操作。
mappingFunctions := map[string]mapper
mappingFunctions ["some_string"] = V1Mapper
然后从另一个文件中,我想这样做:
mappingFunctions["some_string"].ReadMapper(Data)
编辑:我从未在问题中要求语法。我只是想知道是否有更好的方法来做到这一点,因为我是 Go 新手。我同意我对 Go 的语法不是很熟悉,我将不得不阅读文档(不是一次,而是多次)。
最佳答案
如果您想从现有函数组合映射器,您可以使用结构而不是接口(interface):
type Mapper struct {
ReadMapper func(interface{}) interface{}
WriteMapper func(interface{}) interface{}
}
mappers := map[string]*Mapper{}
mappers["some_name"] = &Mapper{
ReadMapper: someFunc1,
WriteMapper: someFunc2,
}
或者
m := new(Mapper)
m.ReadMapper = someFunc1
m.WriteMapper = someFunc2
mappers["some_name"] = m
关于go - 如何实现下面描述的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62149494/