go - 如何通过反射将非指针值复制到指针间接值

标签 go reflection

我希望下面的 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)
    }
}

https://play.golang.org/p/jgEK_rKbgO9

https://play.golang.org/p/B6vOONQ-RXO (紧凑)

关于go - 如何通过反射将非指针值复制到指针间接值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57720308/

相关文章:

google-app-engine - Google App engine-Redislabs Go运行时生产报错-无效内存地址或nil指针解引用

java - 用 Class.forName() 初始化一个类,它有一个带参数的构造函数

go - 如何在 Golang 中将 ast.TypeSpec 断言为 int 类型?

c# - 使用 GetProperties 方法时如何排除静态属性

json - 如何在 GO 中将换行符转换为正确的 JSON?

go - 为什么共享 int 变量在 go 例程中递增时显示原子行为?

.net - 在.NET中使用反射调用泛型方法

c# - 在递归函数中防止 StackOverFlow

go - Handlebars 内的 Hugo 语法文档?

go - 如何获取go语言函数的注解?