go - 如何实现下面描述的功能

标签 go go-interface

我需要做这样的事情:

// I have an interface with these two methods defined
type mapper interface {
    ReadMapper(interface{}) interface{}
    WriteMapper(interface{}) interface{}
}

那么我需要分配ReadMapperWriteMapper在项目的其他地方定义的一些功能。有没有办法在 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/

相关文章:

go - 满足多个接口(interface)的可链接结构方法?

unit-testing - 如何使用相互依赖的接口(interface)方法模拟结构

string - 这两个err值有什么区别?

go - 简单 HTTPS 请求 : Golang returns 505, Python 和 Chrome 工作

git - 如何开发和测试本地 go 模块

apache - Apache2 提供的 HTTPS 请求比通过反向代理慢

go - En/Decode 结构包含许多具有不同实现的接口(interface),每个接口(interface)都带有 gob

go - 未实现,方法类型错误

inheritance - 我如何组织这段从嵌入式类型重新定义方法的 Go 代码,以减少冗余并提高可维护性?

Goroutine 在 Windows 和 Linux 上的行为不同