How to iterate over fields of a struct?


(Oren) #1

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:

It can be reproduced by running go run main.

Thanks!


(Christoph Berger) #2

Why do you want to iterate over the fields of a struct? (I am asking because I feel this might be an xy problem.)


(Leaf Bebop) #3

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.


(Oren) #4

@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?

@Bebop_Leaf Thank you. I’ll give it a try.


(nathankerr) #5

If you Unmarshal the JSON to map[string]interface{} you can easily iterate over the fields.

I would then use something like https://github.com/elgris/sqrl to build the DB update query.


(Christoph Berger) #6

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).


(system) #7

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.