Obtaining the Current Function Name in Go
In order to trace the execution flow of a Go program, it may be desirable to know the current function name. This can be useful for debugging or logging purposes.
To obtain the current function name in Go, one can use the runtime.FuncForPC function, which takes a program counter (PC) as its argument and returns the corresponding function object. Here's an example of how this can be used:
package main import ( "fmt" "runtime" ) func trace() { pc := make([]uintptr, 10) // at least 1 entry needed 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()) } func main() { trace() }
When executed, this program will print the following output:
/path/to/file.go:13 trace
This output indicates that the trace function was called on line 13 of the file file.go.
Note: In Go versions 1.7 and later, it is recommended to use runtime.CallersFrames instead of runtime.FuncForPC. The updated example using runtime.CallersFrames is as follows:
package main import ( "fmt" "runtime" ) func trace() { pcs := make([]uintptr, 10) n := runtime.CallersFrames(2, pcs) frames := runtime.CallersFrames(n) frame, _ := frames.Next() fmt.Printf("%s:%d %s\n", frame.File, frame.Line, frame.Function) } func main() { trace() }
The above is the detailed content of How Can I Get the Current Function Name in Go?. For more information, please follow other related articles on the PHP Chinese website!