how to understand a reflect.ValueOf is addressable ?

80 views
Skip to first unread message

Hyvi

unread,
Jun 25, 2019, 8:57:28 PM6/25/19
to golan...@googlegroups.com
 x := 2
a := reflect.ValueOf(x) //no variable 
b := reflect.ValueOf(&x) //no variable 
c := reflect.ValueOf(&x).Elem() //yes variable 

WHY c is addressable? but a and b not 

Ian Lance Taylor

unread,
Jun 25, 2019, 9:06:02 PM6/25/19
to Hyvi, golang-nuts
On Tue, Jun 25, 2019 at 5:57 PM Hyvi <tanhai...@gmail.com> wrote:
>
> x := 2
> a := reflect.ValueOf(x) //no variable

This is the value of the constant 2, which is not addressable.

> b := reflect.ValueOf(&x) //no variable

This is the value of a pointer, which need not be addressable. For
example, given a map[int]*byte, the value of map[0] is not
addressable.

> c := reflect.ValueOf(&x).Elem() //yes variable

Here the Elem method called on the pointer knows that the returned
value has an address: it's the pointer that was dereferenced. So this
is addressable.

It may help to read https://blog.golang.org/laws-of-reflection .

Ian
Reply all
Reply to author
Forward
0 new messages