Home > Back-end >  Mapping between structs in a loop
Mapping between structs in a loop

Time:10-08

I have a function that does some mapping between 2 structs:

Struct1 => Struct2

where Struct1 is as follows:

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

}

whereas Struct2 looks like this:

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

}

I have a function that maps the "inner" type Transaction => AnotherTransaction, but the issue I have is that there is an outer Struct, named Struct3 for convenience, that is as follows:

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

}

My issue is that from Struct3 I need to access each element of Struct2 and fire up the mapping function above, but I am not sure how to go about it. How can I loop through each element of []Struct2 append each element and return Struct3 now populated with the mapping from mapTo()?

CodePudding user response:

You can update the map function's argument to struct2 and loop through the struct3's fields of array from main function and send each of them to the toMap function.

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

}

  • Related