This is handy for cases such as needing to dynamically assign structs, for example when use with marshalling or when assigning the results of a SQL query into a struct, without duplicating code for each type. This is a naive implementation as it takes absolutely no error checking into account. It is not production safe and is meant to demonstrate how to iterate through and populate a struct.
Example usage
type Foo struct {
Int int
String string
Unassigned string
}
func main() {
foo := &Foo{}
values := map[string]interface{}{
"int": 11,
"string": "foo",
}
assignStructValues(foo, values)
fmt.Println(foo.Int) // 11
fmt.Println(foo.String) // foo
fmt.Println(foo.Unassigned) // still default ""
// note that we still need to assert the value with .(Foo) when we get it back
// if we were dealing with arrays of structs we could cast with .([]Foo)
newFoo := assignNewStruct(foo, values)
fmt.Println(newFoo.(Foo).Int) // 11
}