如何使用反射为未知结构赋值
How to use reflection to assign values to unknown structures
结构可能包含 float32、int32、字符串或指向结构的指针。
这是我的代码。但是我不知道如何给里面的结构体赋值。
type T struct {
A int
B string
C *P
}
type P struct {
A string
B int
}
func main() {
t := T{}
decode(&t, []string{"99", "abc", "abc", "99"})
fmt.Println(t)
}
你可以这样做:
func decode(a interface{}, val []string) {
rdecode(reflect.ValueOf(a).Elem(), val)
}
func rdecode(rv reflect.Value, val []string) int {
var index int
for i := 0; i < rv.NumField(); i++ {
f := rv.Field(i)
if f.Kind() == reflect.Ptr {
if f.IsNil() {
f.Set(reflect.New(f.Type().Elem()))
}
f = f.Elem()
}
switch f.Kind() {
case reflect.Int:
tmp, _ := strconv.Atoi(val[index])
f.Set(reflect.ValueOf(tmp))
index++
case reflect.String:
f.SetString(val[index])
index++
case reflect.Struct:
index += rdecode(f, val[index:])
default:
break
}
}
return index
}
结构可能包含 float32、int32、字符串或指向结构的指针。 这是我的代码。但是我不知道如何给里面的结构体赋值。
type T struct {
A int
B string
C *P
}
type P struct {
A string
B int
}
func main() {
t := T{}
decode(&t, []string{"99", "abc", "abc", "99"})
fmt.Println(t)
}
你可以这样做:
func decode(a interface{}, val []string) {
rdecode(reflect.ValueOf(a).Elem(), val)
}
func rdecode(rv reflect.Value, val []string) int {
var index int
for i := 0; i < rv.NumField(); i++ {
f := rv.Field(i)
if f.Kind() == reflect.Ptr {
if f.IsNil() {
f.Set(reflect.New(f.Type().Elem()))
}
f = f.Elem()
}
switch f.Kind() {
case reflect.Int:
tmp, _ := strconv.Atoi(val[index])
f.Set(reflect.ValueOf(tmp))
index++
case reflect.String:
f.SetString(val[index])
index++
case reflect.Struct:
index += rdecode(f, val[index:])
default:
break
}
}
return index
}