I googled for this issue and found the code for iterating over the fields of a struct. When trying it on my code I got the following error: panic: reflect: call of reflect.Value.NumField on ptr Value
In my case I am reading json file and storing it into a struct. Here is my code:
updatedClicnic is a pointer to a struct, not a struct. So in line 142, it should be v := reflect.ValueOf(updatedClicnic).Elem(). And yes, it would make all fields addressable and setable.
@christophberger - I want to allow a user to update a clinic in my DB by providing a JSON file with some fields that exist in a clinic. so for example you can have a json file with something like this:
{
“name”: “Heal Now”,
“Address”: “3234 Rot Road, Singapore”,
“officeTel”: “65 6100 0939”,
“CreatedBy”: “Doe Joe”,
“hours”: [
{“day”:“mon”, “slot”:1, “opens”: “08:00”, “closes”: “12:00”},
{“day”:“mon”, “slot”:2, “opens”: “13:00”, “closes”: “15:30”},
{“day”:“mon”, “slot”:3, “opens”: “16:00”, “closes”: “19:00”},
{“day”:“tue”, “slot”:1, “opens”: “09:00”, “closes”: “12:30”},
{“day”:“tue”, “slot”:2, “opens”: “13:00”, “closes”: “18:00”}
]
}
in this case only the fields that were found in the JSON file will be updated in the DB.
In order to do that I first have to convert the json into a struct, than I want to go over each field in the struct and if it exist in the clinic struct, i want to update my existing clinic with it.
Does it make sense? maybe there is a better approach?
I second @nathankerr’s advice then. A map supports effortless iterating over its entries.
And if this approach does not meet your needs, and if there is only one single struct involved, consider visiting all of its fields in a hardcoded manner (for example, with a big ugly switch statement where each case tests one of the struct’s fields).