2

The purpose of this blog is to describe how to modify the value of a time variable with a reflection object. To achieve the above goals, the most basic operations are as follows:

Modification of basic data types

 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)
}

The results are as follows:

 num is :  3.14
type:  float64
can set or not: true
6.28

Numerical modification inside the structure

The essence is the same as above, or the pointer address corresponding to the operand value.
Let's first look at how to get the value of the induction, the code is as follows:

 package main

import "fmt"

type Student struct {
    Name   string
    Age    int
    School string
}

func main() {
    s1 := Student{"shilingfly", 18, "TsingHua"}
    fmt.Printf("%T\n", s1)
    p1 := &s1
    fmt.Println(p1.Name)
}

The results are as follows:

 main.Student
shilingfly

Then take a look at how to modify the value of the corresponding field, the code is as follows:

 package main

import (
    "fmt"
    "reflect"
)

type Student struct {
    Name   string
    Age    int
    School string
}

func main() {
    s1 := Student{"shilingfly", 18, "TsingHua"}
    fmt.Printf("%T\n", s1)
    p1 := &s1
    fmt.Println(p1.Name)
    //改变数值
    value := reflect.ValueOf(&s1)
    //看一下是不是reflect的指针类型
    if value.Kind() == reflect.Ptr {
        newValue := value.Elem()
        fmt.Println("can set or not: ", newValue.CanSet())

        //在这里一项一项的修改
        f1 := newValue.FieldByName("Name")
        f1.SetString("Lisome")
        f2 := newValue.FieldByName("Age")
        f2.SetInt(17)
        f3 := newValue.FieldByName("School")
        f3.SetString("MIT")
        fmt.Println(s1)
    }
}

The results are as follows:

 main.Student
shilingfly
can set or not:  true
{Lisome 17 MIT}

Reference: bilibili


LiberHome
409 声望1.1k 粉丝

有问题 欢迎发邮件 📩 liberhome@163.com