Home  >  Article  >  Backend Development  >  How to Retrieve Function Names Using Reflection in Go?

How to Retrieve Function Names Using Reflection in Go?

Susan Sarandon
Susan SarandonOriginal
2024-11-11 13:48:02180browse

How to Retrieve Function Names Using Reflection in Go?

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!

Statement:
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