我希望下面的Set
方法将传入的APtr
结构的B
字段设置为按值传递的值,即没有指针间接作用。>
要通过反射进行工作,我可能必须将该值复制到我有地址的新位置?无论哪种方式,我如何才能使它正常工作?我有一个适用于非指针值的工作版本。
type A struct {
AnInt int
}
type B struct {
AnA A
APtr *A
}
func Set(strukt interface{}, fieldName string, newFieldValue interface{}) {
struktValueElem := reflect.ValueOf(strukt).Elem()
field := struktValueElem.FieldByName(fieldName)
newFieldValueValue := reflect.ValueOf(newFieldValue)
if field.Kind() == reflect.Ptr {
// ?? implement me
} else { // not a pointer? more straightforward:
field.Set(newFieldValueValue)
}
}
func main() {
aB := B{}
anA := A{4}
Set(&aB, "AnA", anA) // works
Set(&aB, "APtr", anA) // implement me
}
答案 0 :(得分:2)
func Set(strukt interface{}, fieldName string, newFieldValue interface{}) {
struktValueElem := reflect.ValueOf(strukt).Elem()
field := struktValueElem.FieldByName(fieldName)
newFieldValueValue := reflect.ValueOf(newFieldValue)
if field.Kind() == reflect.Ptr {
rt := field.Type() // type *A
rt = rt.Elem() // type A
rv := reflect.New(rt) // value *A
el := rv.Elem() // value A (addressable)
el.Set(newFieldValueValue) // el is addressable and has the same type as newFieldValueValue (A), Set can be used
field.Set(rv) // field is addressable and has the same type as rv (*A), Set can be used
} else { // not a pointer? more straightforward:
field.Set(newFieldValueValue)
}
}