Retrieving Function Names Using Reflection
In Go, the reflection system allows for introspection and manipulation of types and values at runtime. However, when retrieving the name of a function using the Name method on its type, an empty string might be returned.
To resolve this issue, use the FuncForPc function from the runtime package. It takes a pointer to a function value and returns a *Func object. This object provides access to the function's name, which can be obtained with the Name method.
Here's a modified version of your example using FuncForPc:
package main import ( "fmt" "reflect" "runtime" ) func main() { name := runtime.FuncForPC(reflect.ValueOf(main).Pointer()).Name() fmt.Println("Name of function :", name) }
This code prints the following output:
Name of function : main.main
If you only require the function name without the package prefix, you can tokenize the Name result.
The above is the detailed content of How to Retrieve Function Names Using Reflection in Go?. For more information, please follow other related articles on the PHP Chinese website!