Home >Backend Development >Golang >How Can I Get Caller Function Information in Golang?
In Golang, it's possible to obtain insights into the caller function. Consider the following code snippet:
func foo() { // Do something } func main() { foo() }
The question arises: how can we determine that foo was invoked from main? Other languages, such as C#, facilitate this task using attributes like CallerMemberName.
Thankfully, Golang provides a solution with the runtime.Caller function.
func Caller(skip int) (pc uintptr, file string, line int, ok bool)
Example #1: Printing Caller File Name and Line Number
package main import ( "fmt" "runtime" ) func foo() { _, file, no, ok := runtime.Caller(1) if ok { fmt.Printf("called from %s#%d\n", file, no) } } func main() { foo() }
Example #2: Retrieving More Information with runtime.FuncForPC
package main import ( "fmt" "runtime" ) func foo() { pc, _, _, ok := runtime.Caller(1) details := runtime.FuncForPC(pc) if ok & details != nil { fmt.Printf("called from %s\n", details.Name()) } } func main() { foo() }
By utilizing these examples, you can effortlessly gain insights into caller function information in Go.
The above is the detailed content of How Can I Get Caller Function Information in Golang?. For more information, please follow other related articles on the PHP Chinese website!