In this tutorial, We are going to learn about Callers function in runtime package in go with example and in details.
The Callers function in runtime package in go returns the function invocation stack for the current goroutine – the lightweight threads managed by the Go runtime. It captures a stack trace by taking a snapshot of the current call stack. The primary usage of ‘Callers‘ is for debugging, logging and tracing.
Syntax:
func Callers(skip int, pc []uintptr) int
The ‘skip‘ parameter specifies the number of stack frames to ascend, with 0 identifying the caller of ‘Callers‘. The ‘pc‘ parameter is a slice to hold the returned program counter values, with the function returning the number of entries written to ‘pc‘.
Example:
package main
import (
"fmt"
"runtime"
)
func main() {
printStack()
}
func printStack() {
pc := make([]uintptr, 10) // at least 1 entry needed
n := runtime.Callers(0, pc)
for _, pc := range pc[:n] {
f := runtime.FuncForPC(pc)
file, line := f.FileLine(pc)
fmt.Printf("%s:%d %s\n", file, line, f.Name())
}
}
In this code, we first create a slice of ‘uintptr‘ with a length of 10. The ‘runtime. Callers function fills this slice with the function pointers of the active stack frames. The function ‘runtime.FuncForPC‘ then allows us to retrieve a ‘*runtime.Func‘ value for each function pointer, from which we can obtain the file name, line number and function name.
Output:
/Users/user_name/go/src/main/main.go:15 main.printStack /Users/user_name/go/src/main/main.go:14 main.printStack /Users/user_name/go/src/main/main.go:10 main.main
To learn more about golang, You can refer given below link:
https://techieindoor.com/go-runtime-package-in-go/
References: