Change the value of a variable by reflect.Value

package main

import (
	"fmt"
	"reflect"
)

func main() {

	n := 1.2345
	fmt.Println("old value :", n)

	//通过reflect.ValueOf获取n中的reflect.Value,注意:参数必须是指针才能修改其值
	v := reflect.ValueOf(&n)
	e := v.Elem()

	fmt.Println("type :", e.Type())
	fmt.Println("can set :", e.CanSet())

	//重新赋值
	e.SetFloat(2.123)
	fmt.Println("new value :", n)

	//nv := reflect.ValueOf(n)
	// 如果非指针,这里直接panic
	//nv.Elem()
}

Operating results:
Old value: 1.2345
of the type: float64
CAN the SET: to true
new new value: 2.123

Published 35 original articles · won praise 3 · views 10000 +

Guess you like

Origin blog.csdn.net/takujo/article/details/102526116