Home >Backend Development >Golang >Is reflection important in golang?
Golang provides a mechanism to update variables, view values at runtime, call methods, and directly modify their layout without knowing the type at compile time. The mechanism of operation is called reflection.
Why use reflection? (Recommended learning: go)
For example, sometimes we need a function that can handle various types of values. Without knowing the type, you might write:
// 伪代码 switch value := value.(type) { case string: // ...一些操作 case int: // ...一些操作 case cbsStruct: // 自定义的结构体 // ...一些操作 // ... }
Have you found any problems?
There is a problem here: there are many types, this function will be very long to write, and there may also be custom types, which means that this judgment may have to be changed in the future, because there is no way to know It is unknown what type the value belongs to.
When you cannot see through an unknown type, the above code is actually not very reasonable. At this time, you need reflection to help you deal with it. Reflection uses the TypeOf and ValueOf functions to obtain the information of the target object from the interface and easily complete the purpose. .
3. What exactly can reflection do?
package main import ( "fmt" "reflect" ) func main() { var name string = "咖啡色的羊驼" // TypeOf会返回目标数据的类型,比如int/float/struct/指针等 reflectType := reflect.TypeOf(name) // valueOf返回目标数据的的值,比如上文的"咖啡色的羊驼" reflectValue := reflect.ValueOf(name) fmt.Println("type: ", reflectType) fmt.Println("value: ", reflectValue) }
Golang provides the reflect package to support reflection. The main ones include two methods and two structs (to be precise, a struct and an interface), which are used to obtain and operate respectively. Dynamic types and dynamic values of interface variables.
Two methods:
func TypeOf(i interface{}) Type {...} This method receives an empty interface type Variables and actual parameters will be copied and converted into empty interface variables, and finally used as parameters of TypeOf.
Within the function, the dynamic type information of the interface variable will be taken out and encapsulated into reflect.Type for return. Because reflect.Type is an interface, what is actually used is an instance of the interface. The real instance here is reflect. .rtype.
func ValueOf(i interface{}) Value {...} With the TypeOf function type, it also receives a copy, and then converts it to an empty interface variable, and takes out the interface variable inside the method The dynamic value is then encapsulated and returned as a reflect.Value object.
The above is the detailed content of Is reflection important in golang?. For more information, please follow other related articles on the PHP Chinese website!