我需要做这样的事情:// I have an interface with these two methods definedtype mapper interface { ReadMapper(interface{}) interface{} WriteMapper(interface{}) interface{}}ReadMapper然后我需要分配WriteMapper一些在项目其他地方定义的功能。有没有办法在 Go 中做这样的事情?给他们分配职能? V1Mapper mapper V1Mapper.ReadMapper = functions().... V1Mapper.WriteMapper = functions()....然后,我需要另一个映射,并希望映射器作为值类型,并希望执行如下操作。mappingFunctions := map[string]mappermappingFunctions ["some_string"] = V1Mapper 然后从另一个文件中,我想这样做:mappingFunctions["some_string"].ReadMapper(Data)编辑:我从未在问题中要求语法。我只是想知道是否有更好的方法来做到这一点,因为我是 Go 新手。我同意我对 Go 的语法不是很熟悉,我将不得不阅读文档(不是一次,而是多次)。
1 回答
素胚勾勒不出你
TA贡献1827条经验 获得超9个赞
如果您想从现有函数组合映射器,您可以使用结构而不是接口:
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
- 1 回答
- 0 关注
- 154 浏览
添加回答
举报
0/150
提交
取消
