How to Retrieve Function Names Using Reflection in Go?

Susan Sarandon
Release: 2024-11-11 13:48:02
Original
186 people have browsed it

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

This code prints the following output:

Name of function : main.main
Copy after login

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!

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