brief introduction
- Reflection is the process of dynamically calling methods and properties of objects
- Reference package:
import ( "reflect" )
- Common methods: reflect.TypeOf() and reflect.ValueOf()
reflect.ValueOf() is used to get the value of the data in the input parameter interface. If the interface is empty, it returns 0
reflect.TypeOf() is used to dynamically get the type of the value in the input parameter interface. If the interface is empty, nil is returned
Basic use
var a = 3 // Get the type of variable, return the reflect.Type type type fmt.Println("Type:", reflect.TypeOf(a)) //Get the value of the variable and return the reflect.Value type v := reflect.ValueOf(a) fmt.Println("Value:", v) fmt.Println("Type:", v.Type()) //Gets the category of the variable and returns a constant fmt.Println("typed constant", v.Kind()) //Convert to interface {} type fmt.Println("Value:", v.Interface())
Output results:
Type: int Value: 3 Type: int Type constant int Value: 3
structural morphology
- TypeOf and ValueOf
// Define a Product type Product struct { Name string `json:"prod_name"` Stock int `json:"stock"` } var prod = Product{ Name: "iphone8", Stock: 5, } prodV := reflect.ValueOf(prod) fmt.Println("Type:", reflect.TypeOf(prod)) fmt.Println("Value:", prodV) fmt.Println("Type constant:", prodV.Kind()) fmt.Println("Value:", prodV.Interface())
Output results:
Type: main.Product Value: {iPhone 8 5} Type constant: struct Value: {iPhone 8 5}
- Use Elem to get the variable the pointer points to
val := reflect.ValueOf(prod) fields := val.NumField() fmt.Println("Number of fields=: ", fields) for i := 0; i < fields; i++ { fmt.Printf("The first%d Type is%s,The value is%v\n", i, val.Field(i).Kind(), val.Field(i)) }
Output results:
Number of fields: 2 The 0 th type is string and the value is iPhone 8 The first type is int and the value is 5
- Get tag
val := reflect.ValueOf(prod) fields := val.NumField() prodT := reflect.TypeOf(prod) for i := 0; i < fields; i++ { tag := prodT.Field(i).Tag.Get("json") fmt.Printf("The first%d One, json value=%s\n", i, tag) }
The output result is:
0, json value = prod_name First, json value = stock
s := reflect.ValueOf(&prod).Elem() for i := 0; i < s.NumField(); i++ { f := s.Field(i) fmt.Printf("Name=%s, type=%s, value=%v\n", s.Type().Field(i).Name, f.Type(), f.Interface()) }
Output results:
Name = name, type = string, value = iPhone 8 Name = Stock, type = int, value = 5
- Set value
s.Field(0).SetString("iphoneX") s.Field(1).SetInt(1) fmt.Println("After amendment:", prod)
Output results:
After modification: {iPhone x 1}