Home >Backend Development >Golang >Can Go Programmatically Retrieve a Function's Name?

Can Go Programmatically Retrieve a Function's Name?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-24 10:02:55902browse

Can Go Programmatically Retrieve a Function's Name?

Retrieving Function Names in Go

Question:

Is it possible to programmatically retrieve the name of a function in Go? For example, given the function foo(), can we determine its name using a method like GetFunctionName(foo)?

Answer:

Yes, it is possible to obtain the name of a function in Go using the runtime.FuncForPC function.

Solution:

Here's a solution using runtime.FuncForPC:

package main

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

func foo() {}

func GetFunctionName(i interface{}) string {
    return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
}

func main() {
    fmt.Println("name:", GetFunctionName(foo))
}

Explanation:

  • reflect.ValueOf(i).Pointer() retrieves the memory address of the function i.
  • runtime.FuncForPC takes the pointer and returns a runtime.Func value.
  • runtime.Func.Name() returns the name of the function associated with the runtime.Func value.

By calling GetFunctionName(foo), you'll get the string "foo" as the result.

The above is the detailed content of Can Go Programmatically Retrieve a Function's Name?. 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