Home > Backend Development > Golang > How to Retrieve a Function's Name Using Reflection in Go?

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

Linda Hamilton
Release: 2024-11-08 15:37:01
Original
487 people have browsed it

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()
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template