Re: [go-nuts] Is there some way to set value for unexported nil ptr field of a struct using reflect?

842 views
Skip to first unread message

Ian Lance Taylor

unread,
Jul 25, 2017, 9:08:50 PM7/25/17
to feilengcui008, golang-nuts
On Sun, Jul 23, 2017 at 12:46 AM, feilengcui008 <feilen...@gmail.com> wrote:
> Hi, all:
> I'm writing a little fuzz tool for struct using reflect package, and
> came across the following case, but didn't find any way to solve it
>
>
> type TestStruct struct {
> a *int // unexported nil ptr field, how to modify it?
> b int // unexported not ptr field, can be modified using
> reflect.NewAt
> C *int // exported nil ptr field, can be modified using
> reflect.New and value.Set
> }
>
> ts := &TestStruct {} // a is nil ptr and not exported
> fieldA := reflect.ValueOf(ts).Elem().Field(0)
> // how to modify the value of a using the reflect value fieldA?

In general you can not use reflect to set unexported fields. If that
were possible, then any package could use reflect to defeat the name
hiding used by any other package, which would make name hiding much
less useful.

Ian

feilengcui008

unread,
Jul 26, 2017, 9:53:33 PM7/26/17
to golang-nuts, feilen...@gmail.com
Thanks for your answer :), even though the original question has been deleted.

I've used the reflect.NewAt to allocate a new memory at the same address of the unexported field's reflect.Value, it seems work.

for unexported not nil field
if !v.CanSet() {
   v
= reflect.NewAt(v.Type(), unsafe.Pointer(v.UnsafeAddr())).Elem()
}

for unexported nil field
// since v is nil value, v.Elem() will be zero value
// and zero value is not addressable or settable, we
// need allocate a new settable v at the same address
v
= reflect.NewAt(v.Type(), unsafe.Pointer(v.UnsafeAddr())).Elem()
newv
:= reflect.New(v.Type().Elem())
v
.Set(newv)



在 2017年7月26日星期三 UTC+8上午9:08:50,Ian Lance Taylor写道:

Matt Harden

unread,
Jul 27, 2017, 10:36:20 PM7/27/17
to feilengcui008, golang-nuts
Just to be clear, when using unsafe it's possible to do pretty much anything; reflect by itself doesn't give you this ability. That's by design AIUI.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

feilengcui008

unread,
Jul 27, 2017, 11:09:02 PM7/27/17
to golang-nuts, feilen...@gmail.com
Ok, I got that, thanks for the clarification!

在 2017年7月28日星期五 UTC+8上午10:36:20,Matt Harden写道:
Reply all
Reply to author
Forward
0 new messages