Home >Backend Development >Golang >How Can I Get the Current Function Name in Go Code?
Introspecting Go Code: Retrieving Current Function Name
In Go, obtaining the current function name is crucial for debugging and tracing. FUNCTION macro in gcc provides this functionality, and we aim to emulate it in Go.
Solution
The key lies in the runtime package. Here's a solution:
import ( "fmt" "runtime" ) func trace() { pc := make([]uintptr, 10) // Need at least 1 entry runtime.Callers(2, pc) f := runtime.FuncForPC(pc[0]) file, line := f.FileLine(pc[0]) fmt.Printf("%s:%d %s\n", file, line, f.Name()) }
This function works by:
Updated Example
For Go versions 1.7 , the recommended approach is to use runtime.CallersFrames instead of runtime.FuncForPC. An updated example below:
import ( "fmt" "runtime" ) func trace() { pc := make([]uintptr, 10) // Need at least 1 entry runtime.CallersFrames(2, pc) frame, _ := runtime.CallersFrames(2, pc) fmt.Printf("%s:%d %s\n", frame[0].File, frame[0].Line, frame[0].Function) }
The above is the detailed content of How Can I Get the Current Function Name in Go Code?. For more information, please follow other related articles on the PHP Chinese website!