I have a struct Person.
type Person struct {
Firstname string
Lastname string
Years uint8
}
Then I have t
Use reflect.ValueOf()
to convert to concrete type. After that you could use reflect.Value.SetString to set the value you want.
structValue := FooBar{Foo: "foo", Bar: 10}
fields := reflect.TypeOf(structValue)
values := reflect.ValueOf(structValue)
num := fields.NumField()
for i := 0; i < num; i++ {
field := fields.Field(i)
value := values.Field(i)
fmt.Print("Type:", field.Type, ",", field.Name, "=", value, "\n")
switch value.Kind() {
case reflect.String:
v := value.String()
fmt.Print(v, "\n")
case reflect.Int:
v := strconv.FormatInt(value.Int(), 10)
fmt.Print(v, "\n")
case reflect.Int32:
v := strconv.FormatInt(value.Int(), 10)
fmt.Print(v, "\n")
case reflect.Int64:
v := strconv.FormatInt(value.Int(), 10)
fmt.Print(v, "\n")
default:
assert.Fail(t, "Not support type of struct")
}
}