In accordance with the Laws of Reflection, it is impossible to set the value of an element as follows, you need to use its address.
This will not work:
var x float64 = 3.4
v := reflect.ValueOf(x)
v.SetFloat(7.1)
This will work:
var x float64 = 3.4
p := reflect.ValueOf(&x)
p.Elem().SetFloat(7.1)
So why the following work when using slices?
floats := []float64{3}
v := reflect.ValueOf(floats)
e := v.Index(0)
e.SetFloat(6)
fmt.Println(floats) // prints [6]
http://play.golang.org/p/BWLuq-3m85
Of course, it v.Index(0)takes a value instead of the address from the slice floats, which means that it should not be installed, as in the first example.
source
share