Golang can change the value of a variable by reflection.
Package main import (" FMT ""reflect" _ "strconv") func main() {var x float64 = 6.6p := reflect.valueof (&x) FMT. Println (p.K ind ()) j: = p.E lem (FMT). The Println (" Val: ", j) j.S etFloat (9.9) FMT. Println (" Val: ", j)}Copy the code
Output:
PTR Val: 6.6 Val: 9.9Copy the code
Note that reflect.valueof (&x) is passed as a pointer type. What happens if we pass a non-pointer?
package main
import (
"fmt"
"reflect"
_ "strconv"
)
type Element interface{}
type List []Element
type Person struct {
name string
age int
}
func (p Person) String() string {
return fmt.Sprintf("name: %s, age: %d", p.name, p.age)
}
func main() {
var x float64 = 6.6
p := reflect.ValueOf(x)
fmt.Println(p.Kind())
j := p.Elem()
fmt.Println("Val:", j)
j.SetFloat(9.9)
fmt.Println("Val:", j)
}
Copy the code
Output:
float64 panic: reflect: call of reflect.Value.Elem on float64 Value goroutine 1 [running]: reflect.Value.Elem(0x10ada00, 0xc000014070, 0x8e, 0x1, 0x1, 0 by 8)/usr/local/Cellar/go / 1.16.6 / libexec/SRC/reflect/value. Go: 843 + 0 x1a5 main. The main ()/XXX/main go: 49 + 0 x14d exit status 2Copy the code
The exception is thrown directly. ValueOf is of type interface{} and returns a Value of type Value. In p.lem (), if p.ind () is neither Interface nor Ptr, then panic is thrown. That is, if the type passed to ValueOf is Interface or Ptr, Elem can be called.