亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

循環中結構之間的映射

循環中結構之間的映射

Go
慕蓋茨4494581 2022-10-04 19:15:31
我有一個函數,可以在2個結構之間做一些映射:Struct1 => Struct2其中如下:Struct1type Struct1 struct {A Transaction `json:"transaction"`B string      `json:"name"`...}而看起來像這樣:Struct2type Struct2 struct {C AnotherTransaction `json:"transaction"`D string      `json:"name"`...}我有一個映射“內部”類型的函數,但我遇到的問題是有一個外部結構,為了方便起見,如下所示:Transaction => AnotherTransactionStruct3type 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的每個元素并啟動上面的映射函數,但我不確定如何去做。我如何遍歷每個元素的附加每個元素,并返回現在填充了來自的映射?[]Struct2Struct3mapTo()
查看完整描述

1 回答

?
30秒到達戰場

TA貢獻1828條經驗 獲得超6個贊

您可以將 map 函數的參數更新為 struct2,并從函數遍歷 struct3 的數組字段,并將每個字段發送到函數。maintoMap


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


}


查看完整回答
反對 回復 2022-10-04
  • 1 回答
  • 0 關注
  • 120 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號