Home > Article > Backend Development > Reflection of golang function
Function reflection in Go provides the ability to obtain and manipulate function information and call it dynamically. The function reflection object can be obtained through reflect.ValueOf, including its signature, parameters and return value information. To call dynamically, build a list of argument reflection values and make the call via f.Call(args), which returns a list of reflection values containing the return value. In practice, this feature can be used to dynamically call methods based on interface types to achieve more flexible code.
Reflection is a powerful feature in Go that allows programs to programmatically obtain and manipulate information about types and values. . Using reflection, we can access the signature, parameters, and return values of a function and call it dynamically.
Usage
To get the reflection object of a function, you can use the reflect.ValueOf
function:
f := reflect.ValueOf(func(x, y int) int { return x + y })
This will create a Reflection object, which contains information about function func
. We can use this reflection object to access the signature, parameters and return value of the function:
f.Type()
Returns the type of the function, Includes the types of parameters and return values. f.NumIn()
Returns the number of parameters of the function, f.In(i)
returns the i
Reflection object for parameters. f.NumOut()
Returns the number of return values of the function, f.Out(i)
Returns the A reflection object that returns i
values. Dynamic Calling
Using reflection, we can call functions dynamically, like this:
args := []reflect.Value{reflect.ValueOf(1), reflect.ValueOf(2)} result := f.Call(args)
args
is a list of reflection objects for function parameter values. f.Call(args)
Call the function and return a list of reflection objects, including the return value.
Practical Case
Let us create a reflection utility that can dynamically call a method that implements an interface based on the interface type:
import ( "fmt" "reflect" ) type Calculator interface { Add(x, y int) int } func ReflectCall(fn interface{}, args []reflect.Value) { fnVal := reflect.ValueOf(fn) if fnType := fnVal.Type(); fnType.Kind() == reflect.Func { result := fnVal.Call(args) fmt.Println(result[0].Interface()) } else { fmt.Println("Not a function!") } } func main() { calc := CalculatorImpl{} ReflectCall(calc.Add, []reflect.Value{reflect.ValueOf(1), reflect.ValueOf(2)}) } type CalculatorImpl struct{} func (c CalculatorImpl) Add(x, y int) int { return x + y }
This program uses the ReflectCall
function to dynamically call the Add
method based on the Calculator
interface type.
The above is the detailed content of Reflection of golang function. For more information, please follow other related articles on the PHP Chinese website!