【问题标题】:Mapping between structs in a loop循环中结构之间的映射
【发布时间】:2021-11-26 20:03:11
【问题描述】:

我有一个函数可以在 2 个结构之间进行一些映射:

Struct1 => Struct2

其中Struct1如下:

type Struct1 struct {
A Transaction `json:"transaction"`
B string      `json:"name"`
...

}

Struct2 看起来像这样:

type Struct2 struct {
C AnotherTransaction `json:"transaction"`
D string      `json:"name"`
...

}

我有一个映射“内部”类型Transaction => AnotherTransaction的函数,但我遇到的问题是有一个外部结构,为方便起见,命名为Struct3,如下所示:

type Struct3 struct {
    Failed   []Struct2 `json:"failed"` // a list of transactions
    Success  []Struct2 `json:"success"`
}

func mapTo(st3 Struct3) Struct1 {
  st1 := Transaction{}
  // the mapping between A => C is quite lengthy
  st1.someField = st3.struct2.anotherField

  return st1 // now mapped

}

我的问题是,我需要从 Struct3 访问 Struct2 的每个元素并启动上面的映射函数,但我不知道该怎么做。如何循环遍历[]Struct2 的每个元素,追加每个元素并 return Struct3 现在填充来自mapTo() 的映射?

【问题讨论】:

    标签: loops go struct


    【解决方案1】:

    您可以将 map 函数的参数更新为 struct2 并从 main 函数循环遍历 struct3 的数组字段,并将它们中的每一个发送到 toMap 函数。

    func main() {
        type Struct3 struct {
            Failed   []Struct2 `json:"failed"` // a list of transactions
            Success  []Struct2 `json:"success"`
        }
        s3 := &Struct3{
            Failed: make([]Struct2, 0),
            Success: make([]Struct2, 0),
        }
    
        for i := range s3.Success {
            // do something with the result value
            _ = toMap(s3.Success[i])
        }
    
        for i := range s3.Failed {
            // do something with the result value
            _ = toMap(s3.Failed[i])
        }
    }
    
    func mapTo(st2 Struct2) Struct1 {
      st1 := Transaction{}
      // the mapping between A => C is quite lengthy
      st1.someField = st2.anotherField
    
      return st1 // now mapped
    
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-11
      • 2020-10-20
      • 1970-01-01
      • 1970-01-01
      • 2017-07-26
      • 2012-03-31
      • 1970-01-01
      相关资源
      最近更新 更多