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

去游乐场: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))

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


拉莫斯之舞
浏览 71回答 1
1回答

尚方宝剑之说

下面的代码应该可以工作。如果该字段是一个指针,它会创建该指针所指向的类型的实例,并对其进行设置。    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)
打开App,查看更多内容
随时随地看视频慕课网APP