Obtaining Caller Information in GoLang
Is it feasible to determine information about the function that invoked another function in GoLang? If a function, such as foo() below, is called from main(), how can we find out?
func foo() { // Perform some actions } func main() { foo() }
While some languages, such as C#, provide features like the CallerMemberName attribute to retrieve this data, GoLang employs a different approach.
Solution: runtime.Caller
GoLang offers the runtime.Caller function for acquiring information about the caller. Here's its syntax:
func Caller(skip int) (pc uintptr, file string, line int, ok bool)
Example 1: Displaying 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: Gathering Detailed Information with runtime.FuncForPC
For more comprehensive information, you can use runtime.FuncForPC in conjunction with runtime.Caller:
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() }
The above is the detailed content of How Can I Get Caller Information in Go?. For more information, please follow other related articles on the PHP Chinese website!