Menu Close

Caller in runtime package in go

In this tutorial, We are going to learn about Caller function in runtime package in go with example and in details.

The Caller function in runtime package in go is defined as ‘runtime.Caller()‘ in the runtime package. This function retrieves information about the function that is ‘n’ stack frames above the current function on the call stack. It returns the program counter (PC) for the function, the file name and the line number of the source code where the function was called, as well as a boolean value indicating whether the function call was successful.

Syntax:

func Caller(skip int) (pc uintptr, file string, line int, ok bool)

Where ‘skip‘ is the number of stack frames to ascend, with 0 being the Caller function itself, 1 being the function that called Caller, and so on.

Usage of the Caller Function:

The Caller function is useful when you need to obtain information about the call stack, such as in logging, debugging, or tracing code execution. By providing a ‘skip‘ value, you can control which function on the call stack you want to retrieve information about.

Example:

package main


import (

	"fmt"

	"runtime"

)


func main() {

	fmt.Println("Program execution started.")

	exampleFunction()

	fmt.Println("Program execution completed.")

}


func exampleFunction() {

	showCallerInfo(1)

}


func showCallerInfo(skip int) {

	pc, file, line, ok := runtime.Caller(skip)

	if !ok {

		fmt.Println("Failed to retrieve caller information.")

		return

	}

	funcName := runtime.FuncForPC(pc).Name()


	fmt.Printf("Function: %s\nFile: %s\nLine: %d\n", funcName, file, line)

}

In the example above, the ‘exampleFunction()‘ calls the ‘showCallerInfo()‘ function, which uses the ‘runtime.Caller()‘ function to retrieve information about the function that called it. In this case, the ‘skip‘ value is 1, which corresponds to the ‘exampleFunction()‘ call.

When you run this code, you will see output similar to the following:

Output:

Program execution started.
Function: main.exampleFunction
File: /path/to/your/go/file.go
Line: 12
Program execution completed.

To learn more about golang, You can refer given below link:

https://www.techieindoor.com/go-runtime-package-in-go/

References:

https://golang.org/pkg/

Posted in golang, packages, runtime

Leave a Reply

Your email address will not be published. Required fields are marked *