Why can I set a value in a slice using reflection?

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) // Error: will panic.

This will work:

var x float64 = 3.4
p := reflect.ValueOf(&x) // Note: take the address of 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.

+4
source share
1 answer

x. x reflect.ValueOf. v.SetFloat, , x.

x, , .

floats reflect.ValueOf, . "Slice " (http://golang.org/doc/effective_go.html#slices). , . (append co), , .

+7
source

Source: https://habr.com/ru/post/1546200/


All Articles