这篇博客的目标是介绍如何用反射对象批改工夫变量的值。要达到上述目标,最根本的操作如下:
package main
import (
"fmt"
"reflect"
)
func main() {
var num float64 = 3.14
fmt.Println("num is : ", num)
//上面操作指针获取num地址,记得加上&取地址
pointer := reflect.ValueOf(&num)
newValue := pointer.Elem()
fmt.Println("type: ", newValue.Type())
fmt.Println("can set or not:", newValue.CanSet())
//从新赋值
newValue.SetFloat(6.28)
fmt.Println(num)
}
运行后果如下:
num is : 3.14
type: float64
can set or not: true
6.28
发表回复