我希望下面的 Set
方法将传入的 B
结构的 APtr
字段设置为按值传入的值,即没有指针间接寻址。
为了通过 go 反射工作,我可能必须将该值复制到我有地址的新位置?不管怎样,我怎样才能让它发挥作用?我拥有的是非指针值的工作版本。
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
}
Playground :https://play.golang.org/p/6tcmbXxBcIm
最佳答案
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)
}
}
关于go - 如何通过反射将非指针值复制到指针间接值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57720308/