Retrieve Function Name with Reflection
In Go, reflection provides the mechanism to inspect and manipulate program structures at runtime. Accessing a function's name is one such use case. However, attempting to obtain the name directly from its type may result in an empty string.
Expected Behavior
Retrieving a function's name using reflect.TypeOf(function).Name() returns an empty string as it points to the type itself, which doesn't hold the function's name.
Solution
To retrieve the function's name, we need to utilize runtime.FuncForPC. This function takes the pointer to the function's reflected value and returns a pointer to a *Func struct. Calling the Name method on this *Func yields the expected function name as:
name := runtime.FuncForPC(reflect.ValueOf(function).Pointer()).Name()
This approach returns both the package and function name, e.g. "package.function". If desired, the package name can be extracted by tokenizing the string.
The above is the detailed content of How to Retrieve a Function's Name Using Reflection in Go?. For more information, please follow other related articles on the PHP Chinese website!