关于go:Go-通过反射的reflect设置实际变量的值

2次阅读

共计 384 个字符,预计需要花费 1 分钟才能阅读完成。

这篇博客的目标是介绍如何用反射对象批改工夫变量的值。要达到上述目标,最根本的操作如下:

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
正文完
 0