【发布时间】: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() 的映射?
【问题讨论】: