当前函数的名称[重复]

This question already has an answer here:

Is there a way to include the name of the current function I am in? I'd like to include it in my debug logs rather than hard coding the func name which is a pain after a while.

Thanks.

</div>

You can do this using 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()
}

Outputs (package.function)

main.foo