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

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

DDD
DDDOriginal
2024-11-09 19:44:02636browse

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

Retrieving Function Name via Reflection

Reflecting on a function's type does not yield its name. Instead, employ the FuncForPc utility to retrieve a *Func instance. This instance provides access to the function's name, formatted as package-qualified, e.g., "main.main". If the unqualified name is desired, simply tokenize the result.

import (
    "fmt"
    "reflect"
    "runtime"
)

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

The above is the detailed content of How Can I Retrieve a Function's Name 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