How to access unexported struct fields in Golang?

前端 未结 3 1668
我在风中等你
我在风中等你 2020-12-09 10:48

Is there a way to use Reflect to access unexported fields in go 1.8? This no longer seems to work: https://stackoverflow.com/a/17982725/555493

Note that reflec

3条回答
  •  长情又很酷
    2020-12-09 11:53

    Based on cpcallen's work:

    import (
        "reflect"
        "unsafe"
    )
    
    func GetUnexportedField(field reflect.Value) interface{} {
        return reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).Elem().Interface()
    }
    
    func SetUnexportedField(field reflect.Value, value interface{}) {
        reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).
            Elem().
            Set(reflect.ValueOf(value))
    }
    
    

    reflect.NewAt might be confusing to read at first. It returns a reflect.Value representing a pointer to a value of the specified field.Type(), using unsafe.Pointer(field.UnsafeAddr()) as that pointer. In this context reflect.NewAt is different than reflect.New, which would return a pointer to a freshly initialized value.

    Example:

    type Foo struct {
        unexportedField string
    }
    
    GetUnexportedField(reflect.ValueOf(&Foo{}).Elem().FieldByName("unexportedField"))
    

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

提交回复
热议问题