Home > OS >  Golang array with forEach to fill model
Golang array with forEach to fill model

Time:05-29

I have a dynamic import where people can choose what field to use for a specific row. In Golang, I receive this array obviously and want to loop through the imported CSV and add each row to a specific part of the model. See my current code below.

applicant := models.Applicant{
    Prefix:                        "",
    FirstName:                     "",
    LastName:                      "",
    Email:                         "",
    Telephone:                     "",
    Mobile:                        "",
    Gender:                        "",
    CreatedAt:                     time.Time{},
    UpdatedAt:                     nil,
    DeletedAt:                     nil,
}

row := 0
splitted := strings.Split(details[0], ",")
data := strings.Split(rec[0], ";")

for i := range splitted {
    if splitted[i] != "" {    
        applicant[splitted[i]] = data[row]
    }

    row  
}

Obviously this won't work because I cannot say (in my for loop):

applicant[splitted[i]] = data[row]

Because a model does not support indexing. I have been Googling for hours but I am unable to find a solution to my problem.

Can anyone please help me out and tell me how I can make this work?

CodePudding user response:

If that model is an arbitrary structure, you might need to use reflection on order to modify one of its fields.

See for instance this answer, which adds a SetStringField2() method, using a Value.SetString() call to modify the (string) value of a field.

Example:

    a := struct {
        Name string
    }{}

    // works
    reflect.ValueOf(&a).Elem().FieldByName("Name").SetString("Hello")
    fmt.Printf("%#v\n", a)
  •  Tags:  
  • go
  • Related