创建满足接口的结构

时间:2020-06-15 17:20:54

标签: go struct interface

我正在创建一个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对象转换为新的balance结构,以便将它们全部存储为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

            }
        }
    }

在上面的循环中,我检查数据的映射条目是否与注册表中的条目相同。如果是,那么我想使用与注册表项相同类型的数据创建新值,以便它们全部实现我的接口。由于它们是接口类型,因此我似乎无法使用struct方法,例如

func (b Balance) NewBalance(Unique string) *Balance {
    return &Balance{
        Unique: Unique,
    }
}

我只能访问Transformer方法。我是否缺少一种方法来创建满足循环中接口要求的结构实例?

0 个答案:

没有答案
相关问题