Home >Backend Development >Golang >Can Go Programmatically Retrieve a Function's Name?
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:
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!