I’m having the below code that is creating a struct using reflection:
package main
import (
"fmt"
"reflect"
)
func main() {
name := "Myfield"
age := 25
t := reflect.StructOf([]reflect.StructField{
{
Name: reflect.ValueOf(name).Interface().(string),
Type: reflect.TypeOf(age),
Tag: `json:"name"`,
},
})
v := reflect.New(t)
e := v.Elem()
e.Field(0).SetInt(1234)
d := e.Addr().Interface()
fmt.Printf("value: %+#v\n", d)
}
I need to add other fields to this struct based on some definistion in other place, let’s say something like:
fields := []string{"area", "size"}
types := []interface{}{5, 10.3}
for i, v := range fields {
x := reflect.StructField{
Name: reflect.ValueOf(v).Interface().(string),
Type: reflect.TypeOf(types[i]),
}
t = append(t, x)
}
But the t = append(t, x) looks to be wrong, how can I add the fileds defined in the range over the slices to the []reflect.StructField of the struct t
package main
import (
"reflect"
)
func CreateStruct() reflect.Value {
f := []reflect.StructField{}
fields := []string{"Myfield", "Area", "Size"}
types := []interface{}{25, 5, 10.3}
for i, v := range fields {
x := reflect.StructField{
Name: reflect.ValueOf(v).Interface().(string),
Type: reflect.TypeOf(types[i]),
}
f = append(f, x)
}
t := reflect.StructOf(f)
e := reflect.New(t).Elem()
return e
}
And call and manipulate it as:
func main() {
e := CreateStruct() // reflect.Value
e.FieldByName("Area").SetInt(1234)
fmt.Printf("value: %+#v\n", e)
fmt.Printf("value: %+#v %+#v\n", e.FieldByName("Myfield"), e.FieldByName("Area"))
s := e.Addr().Interface()
w := new(bytes.Buffer)
if err := json.NewEncoder(w).Encode(s); err != nil {
panic(err)
}
fmt.Printf("value: %+v\n", s)
fmt.Printf("json: %s", w.Bytes())
rx := bytes.NewReader([]byte(`{"Myfield":0,"Area":1234,"Size":20}`))
if err := json.NewDecoder(rx).Decode(s); err != nil {
panic(err)
}
fmt.Printf("value: %+v\n", s)
}
The output of teh above is:
```bash
value: struct { Myfield int; Area int; Size float64 }{Myfield:0, Area:1234, Size:0}
value: 0 1234
value: &{Myfield:0 Area:1234 Size:0}
json: {"Myfield":0,"Area":1234,"Size":0}
value: &{Myfield:0 Area:1234 Size:20}