I have a struct v with members A, B, C string. Using reflection, I can get the names of the fields and their values:
typ := v.Type()
for i := 0; i < v.NumField(); i++ {
// gets us a StructField
fi := typ.Field(i)
fieldname := fi.Name
fmt.Println(fieldname)
val := fmt.Sprintf("%v", v.Field(i).Interface())
}
since I have the name, and can get the value OUT, can I assign new values to the fields? I would like to do essentially:
v.Field(fieldname).Interface() = "new value"
but that obviously doesn't work. Is it possible to assign a value into a struct if you only know the name of the field?
In practice, I'm trying to assign values from a map[string]string
to corresponding fields in a struct, where the struct and map definitions may expand of change over time, and the map may contain more, or less, values than the struct. I've considered doing it w/JSON, but that approach leaves me a little cold, seeing as how easy it was to use reflection to get "almost" there!
Thanks, Ken