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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3