golang 反射,将结构的第一个值设置为零值



>go playground: https://play.golang.org/p/ck3PtydW3YT

我有一个这样的结构:

type Input struct {
InputA *InputA
InputB *InputB
InputC *InputC
}

我正在尝试使用反射将第一个值(在本例中为 *InputA(设置为其零值 (&InputA{}(,但它不起作用:

actionInput = Input{}
v := reflect.ValueOf(actionInput)
i := 0
typ := v.Field(i).Type()
inputStruct := reflect.New(typ).Elem().Interface()
reflect.ValueOf(&actionInput).Elem().Field(i).Set(reflect.ValueOf(inputStruct))

我猜这是因为它是一个指针,但我不确定如何解决这个问题

下面的代码应该可以工作。如果字段是指针,它将创建该指针指向的类型的一个实例,并对其进行设置。

typ := v.Field(i).Type()
var inputStruct reflect.Value
if typ.Kind()==reflect.Ptr {
inputStruct=reflect.New(typ.Elem())
} else {
inputStruct = reflect.New(typ).Elem()
}
reflect.ValueOf(&actionInput).Elem().Field(i).Set(inputStruct)

最新更新