"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Retrieve a Function's Name Using Reflection in Go?

How to Retrieve a Function's Name Using Reflection in Go?

Published on 2024-11-10
Browse:192

How to Retrieve a Function's Name Using Reflection in Go?

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.

Latest tutorial More>

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