Home  >  Article  >  Backend Development  >  [Summary] Some common Golang reflection usages

[Summary] Some common Golang reflection usages

PHPz
PHPzOriginal
2023-03-30 09:11:04648browse

Golang is a statically typed programming language, but it also provides a reflection mechanism that can obtain the type information of variables at runtime, as well as dynamically call methods and modify properties. Reflection is a common feature in Golang programming. This article will introduce some common usage of Golang reflection.

Basic knowledge of reflection

Reflection is an important feature of Golang, which allows the program to dynamically identify object types and perform operations at runtime. Through reflection, we can access all members, methods, labels and other information of a structure.

In Golang, reflection can be used to complete the following three tasks:

  1. Query the type information of the variable
  2. Get the actual value of the variable
  3. Modify the value of a variable

Reflection is mainly implemented by the reflect standard library. By calling some methods in the reflect library, you can obtain the type and value of the variable. and other related information.

Common usage of reflection

Get the type of variable

Through reflection, we can get the type information of any variable. The following is an example of obtaining the variable type:

package main

import (
    "fmt"
    "reflect"
)

func main() {
    var num int = 100
    fmt.Println(reflect.TypeOf(num))
}

Running the above code will output the type int of the variable num.

Get the value of a variable

In Golang, the actual value of any variable can be obtained through reflection. The following is an example of obtaining the value of a variable:

package main

import (
    "fmt"
    "reflect"
)

func main() {
    var num int = 100
    fmt.Println(reflect.ValueOf(num))
}

Running the above code will output the value 100 of the variable num.

Modify the value of the variable

Through reflection, we can not only obtain the type and value of the variable, but also modify the value of the variable. The following is an example of modifying the value of a variable:

package main

import (
    "fmt"
    "reflect"
)

func main() {
    var num int = 100
    fmt.Println("before:", num)

    value := reflect.ValueOf(&num)
    value.Elem().SetInt(200)

    fmt.Println("after:", num)
}

Running the above code will output the value of variable num before and after modification.

Get the member information of the structure

In Golang, we can obtain the member information of the structure through reflection. The following is an example of obtaining structure member information:

package main

import (
    "fmt"
    "reflect"
)

type User struct {
    Name string
    Age  int
}

func main() {
    user := &User{Name: "Tom", Age: 18}
    
    t := reflect.TypeOf(user).Elem()
    for i := 0; i < t.NumField(); i++ {
        field := t.Field(i)
        fmt.Println(field.Name)
        fmt.Println(field.Type)
        fmt.Println(field.Tag)
    }
}

Running the above code will output all member information of structure User.

Dynamic call function

Through reflection, we can dynamically call functions. The following is an example of dynamically calling a function:

package main

import (
    "fmt"
    "reflect"
)

func Sum(a, b int) int {
    return a + b
}

func main() {
    fn := reflect.ValueOf(Sum)
    args := []reflect.Value{reflect.ValueOf(1), reflect.ValueOf(2)}

    result := fn.Call(args)
    fmt.Println(result[0].Int())
}

Running the above code will output the result 3 calculated by function Sum. In function Call, the parameter args is a slice, which stores the parameter values ​​of the function. In the same way, you can also use reflect.ValueOf to dynamically call methods. However, it should be noted that the first parameter of the method is the receiver object, which needs to be wrapped with reflect.ValueOf.

Summary

This article introduces the common uses of Golang reflection, including obtaining variable types, obtaining variable values, modifying variable values, obtaining member information of structures, dynamically calling functions, etc. I believe these reflection usages can help you better understand and use Golang's reflection mechanism.

The above is the detailed content of [Summary] Some common Golang reflection usages. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn