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.

On Wed, Jul 26, 2017 at 6:53 PM feilengcui008 <feilengcui...@gmail.com>
wrote:

> 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写道:
>
>> 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
>>
> --
> 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+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>

-- 
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+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to