How to Use Reflect to Set a Struct Field
Golang reflect package is one of the hardest to understand.
Yet reflect is one of the most powerful because you can inspect a struct and it’s fields during runtime, and change it.
Go isn’t as simple to understand as other languages such as Python in using reflection. Just try reading their laws of reflection.
But setting a field of a struct by name could be a one liner. There is a nice answer in Stack Overflow.
In short, if you want to set a struct
foo object when you know the field name to set, this is the code:
1 2 3 4 5 6
If you want to print all the fields of
foo, this is the code:
1 2 3 4 5 6 7