Home > Enterprise >  populate struct fields in Go by looping over data from another function
populate struct fields in Go by looping over data from another function

Time:01-25

I have a couple handlers in a web app (Fiber framework) where one handler retrieves data from an external API and the other handler takes a subset of this data and performs some business logic (ie sends a report, etc).

Both handlers are in the same package. In handler2.go I am able to dereference the data from handler1.go and I want to use specific values from that data to populate the struct fields in handler2.go. The dereferenced data from handler1.go is itself an array of structs that I can loop over.

In handler2.go , I have a struct:

type Report struct {
  contact  string
  date     string
  resource string
}

// get data from handler1.go function and use it to populate the Report struct
// each "report" is a struct, so need to create a list of structs
func getReportData() {
   reportData := GetReport() // call function in handler1.go
   for _, report := range *reportData {
   fmt.Println(report.Date)
}

So instead of simply printing the data (the print statement is just to show that I have access to the data I need) I want to populate the Report struct with specifc items from the data that I can can access using the loop and the report.<KEY> syntax.

How can I create a list of structs (using the Report struct) populated with the data I can get via this for loop?

For an MVP , I can simply format this list of structs (in json) and display an endpoint in the web app. I am just struggling with how to construct this data properly.

CodePudding user response:

To answer the direct question, if we assume that the values returned by GetReport() have Date, Contact, and Resource fields, then you could write:

type Report struct {
  contact  string
  date     string
  resource string
}

// Return a list (well, slice) of Reports
func getReportData() (reports []Report) {
  reportData := GetReport()
  for _, report := range reportData {
    myReport := Report{
      contact:  report.Contact,
      date:     report.Date,
      resource: report.Resource,
    }

    reports = append(reports, myReport)
  }

  return
}
  • Related