O'Reilly logo

The Go Programming Language by Brian W. Kernighan, Alan A. A. Donovan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

12.5 Setting Variables with reflect.Value

So far, reflection has only interpreted values in our program in various ways. The point of this section, however, is to change them.

Recall that some Go expressions like x, x.f[1], and *p denote variables, but others like x + 1 and f(2) do not. A variable is an addressable storage location that contains a value, and its value may be updated through that address.

A similar distinction applies to reflect.Values. Some are addressable; others are not. Consider the following declarations:

x := 2                     // value   type   variable?
a := reflect.ValueOf(2)    // 2       int    no
b := reflect.ValueOf(x)    // 2       int    no
c := reflect.ValueOf(&x)   // &x      *int   no
d := c.Elem()              // 2       int    yes (x)

The value ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required