Member-only story
Go reflection
Reflection overview
Reflection is the ability to access, inspect, and modify objects dynamically while a program is running. In statically typed languages, type information is usually determined at compilation time, while reflection allows programs to obtain and process type information dynamically at runtime.
The reflection mechanism in Go language is provided by the reflect package, which provides some functions and structures that allow the program to obtain the type information, value and method of variables at runtime.
Reflection is useful in some situations, such as when working with dynamic data such as configuration files and JSON , or when implementing general serialization and deserialization frameworks.
Reflection foundation
The Type and Value structs in the reflect package are the basis of the reflection mechanism. The Type struct represents Metadata information for a type, while the Value struct represents Metadata information for a value.
We can use the reflect. TypeOf () function to get the Type information of a value, and use the reflect. ValueOf () function to get the Value information of a value.
Here is a simple example:
package main
import (
"fmt"
"reflect"
)
func main() {…