我试图实现一个方法来改变可以具有任意结构的对象中的字段的值.当我有一个指向一个结构体的指针时,字段的转换就没有问题.但是当我有一个接口不包含指向结构体的指针但结构本身时,我无法设法更改这些字段:简而言之
@H_404_12@// The following doesn't work var x interface{} = A{Str: "Hello"} // This panics: reflect: call of reflect.Value.Field on ptr Value reflect.ValueOf(&x).Field(0).SetString("Bye") // This panics: reflect: call of reflect.Value.Field on interface Value reflect.ValueOf(&x).Elem().Field(0).SetString("Bye") // This panics: reflect: reflect.Value.SetString using unaddressable value reflect.ValueOf(&x).Elem().Elem().Field(0).SetString("Bye") // This prints `false`. But I want this to be settable fmt.Println(reflect.ValueOf(&x).Elem().Elem().Field(0).CanSet()) // This works var z interface{} = &A{Str: "Hello"} // This prints `true` fmt.Println(reflect.ValueOf(z).Elem().Field(0).CanSet())
长期:http://play.golang.org/p/OsnCPvOx8F
我已经阅读了The Laws of Reflection,所以我知道,当我有一个指向结构体的指针时,我只能修改字段.所以我的问题现在是:如何获取指向结构数据的指针?
更新:
我使用基本上y:= reflect.New(reflect.TypeOf(x))使它工作,所以y的值现在可以设置.有关广泛的示例,请参阅:https://gist.github.com/hvoecking/10772475