您可以使用 runtime.Callers
package main
import (
"fmt"
"runtime"
)
func printFuncName() {
fpcs := make([]uintptr, 1)
// Skip 2 levels to get the caller
n := runtime.Callers(2, fpcs)
if n == 0 {
fmt.Println("MSG: NO CALLER")
}
caller := runtime.FuncForPC(fpcs[0] - 1)
if caller == nil {
fmt.Println("MSG CALLER WAS NIL")
}
// Print the name of the function
fmt.Println(caller.Name())
}
func foo() {
printFuncName()
}
func main() {
foo()
}
Run Code Online (Sandbox Code Playgroud)
输出(包.函数)
main.foo