go - 创建满足接口的结构
问题描述
我正在创建一个 Go 应用程序,它将一些数据作为字节,然后尝试从该数据生成一些状态。我的应用程序包含一个注册表,其中包含一个实现 Transformer 接口的结构列表,该接口包含用于序列化和散列数据的某些方法。
// Transformer contains some sort of transform logic
Transformer() {
Unique() string
common.Applicator
common.Hasher
common.Packer
}
这是一个实现接口的结构体,它具有以下字段,并且接口方法都已实现。
// Balance implements the Transformer interface.
type Balance struct {
From string `json:"from"`
To string `json:"to"`
Amount string `json:"amount"`
Unqiue string `json:"unique"`
}
我遇到的问题是数据是这样进来的。在这里,我有 balance,它是实现 Transformer 接口的结构的唯一名称,以及与上面的 balance 结构相关的值数组。
`
{
"balance":[
{
"unique":"balance",
"amount":21,
"to":"JoeB"
},
{
"unique":"balance",
"amount":24,
"to":"JohnDoe"
}
]
}
`
我现在想将所有这些 JSON 对象转换为新的平衡结构,以便我可以将它们全部存储为 Transformer 接口类型的列表。但是,由于我可以注册多种实现 Transformer 接口的类型,因此我需要一种方法来确定循环时该类型应该是什么。
initialBytes := make(map[string][]interface{})
err := s.Unmarshal(i, &initialBytes)
if err != nil {
return nil, err
}
for unique, model := range registry.Transforms {
if values, ok := initialBytes[unique]; ok {
for _, v := range values {
// I need a way here of creating structs of type model
}
}
}
在上面的循环中,我检查数据的映射条目是否与我的注册表中的条目相同。如果是,我想使用与注册表项相同类型的数据创建新值,以便它们都实现我的接口。由于它们是接口类型,我似乎无法使用结构方法,例如,如果我有
func (b Balance) NewBalance(Unique string) *Balance {
return &Balance{
Unique: Unique,
}
}
我只能访问 Transformer 方法。我在这里缺少一种方法来创建满足循环中接口的结构实例吗?
解决方案
推荐阅读
- java - Java Opencsv 使用 csv 文件中的(名字中的双引号)和(双引号中的名字中的逗号)列解析 csv
- flutter - 如何根据设备屏幕在颤动中调整容器
- javascript - 如何使用 JavaScript(js) 克隆和删除 html 表单?
- c++ - 带有自定义删除器的 std::unique_ptr 对象的大小(带有按引用捕获的 lambda)
- c# - 实体框架核心,更新数据库不考虑属性
- reactjs - SyntaxError:React 项目中的令牌无效或意外
- flutter - Flutter:Checkbox onChange 不会更新 UI,即使值更改也很困难
- docker - 我必须在 kubernetes 上的 mosquitto 代理中订阅/发布哪个 IP
- php - Laravel 删除查询在哪里为空
- unity3d - 如何禁用游戏对象,使其在再次启动游戏时不会再次打开