首页 > 解决方案 > 创建满足接口的结构

问题描述

我正在创建一个 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 方法。我在这里缺少一种方法来创建满足循环中接口的结构实例吗?

标签: gostructinterface

解决方案


推荐阅读