golang反射将结构的第一个值设置为其零值
前往游乐场: 我有一个类似的结构:golang反射将结构的第一个值设置为其零值,go,reflection,Go,Reflection,前往游乐场: 我有一个类似的结构: type Input struct { InputA *InputA InputB *InputB InputC *InputC } 我试图使用反射将第一个值(在本例中为*InputA)设置为其零值(&InputA{}),但它不起作用: actionInput = Input{} v := reflect.ValueOf(actionInput) i := 0 typ := v.Field(i).Ty
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)
您正在将第一个字段设置为其零值。指针的零值为零。如果需要将其设置为指向结构零值的指针,则必须创建该结构的新实例,获取指向该结构的指针,然后进行设置。这就是我在定义
inputStruct
时尝试的操作,但显然这会创建一个新的“*InputA”,而不是新的“InputA”。这是有道理的,但我不知道如何按照我的意图解决这个问题。如果您想要一个新的InputA
,它将是reflect.new(v.Field(I).Elem().Type()).Interface()
。