Home > Backend Development > Golang > How to Obtain the Name of a Function Using Go Reflection?

How to Obtain the Name of a Function Using Go Reflection?

Linda Hamilton
Release: 2024-11-12 20:45:02
Original
1029 people have browsed it

How to Obtain the Name of a Function Using Go Reflection?

Understanding Reflection in Go: Retrieving Function Names

In Go's reflection system, retrieving the name of a function is not as straightforward as it may seem. The expected behavior, in certain scenarios, is to obtain an empty string when calling Name method.

Unexpected Empty String:

When using the following code snippet, the Name method returns an empty string:

package main

import "fmt"
import "reflect"

func main() {
    typ := reflect.TypeOf(main)
    name := typ.Name()
    fmt.Println("Name of function: " + name)
}
Copy after login

In this example, we attempt to retrieve the name of the main function using reflection. However, the output reads "Name of function: ," indicating an empty name.

Solution using runtime.FuncForPC:

The key to resolving this issue lies in utilizing the runtime.FuncForPC function. This function returns a pointer to a Func type, which provides additional information about the function, including its name.

package main

import "fmt"
import "reflect"
import "runtime"

func main() {
    name := runtime.FuncForPC(reflect.ValueOf(main).Pointer()).Name()
    fmt.Println("Name of function: " + name)
}
Copy after login

Now, the result will be "main.main," which accurately reflects the name of the function. If you wish to extract only the function name without the package name, you can split the string using the strings.SplitN function.

The above is the detailed content of How to Obtain the Name of a Function Using Go Reflection?. 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