Golang: Get the function caller’s name


Consider this code:

package main 

import "fmt"

func foo() {
    // foo() wants to know who called it

func main() {

In the function foo, we want to get the name of the function (and preferably file name and number ) that called it.


We can get this information by traversing the stack trace (which Go’s “runtime” package has handy functions for:

func foo() {
    fpcs := make([]uintptr, 1)
    // Skip 2 levels to get the caller
    n := runtime.Callers(2, fpcs)
    if n == 0 {
        fmt.Println("MSG: NO CALLER")

    caller := runtime.FuncForPC(fpcs[0]-1)
    if caller == nil {
        fmt.Println("MSG CALLER WAS NIL")

    // Print the file name and line number

    // Print the name of the function

By Moazzam

Moazzam is a software developer working in the big apple. He has over a decade of experience in development. While most of his work involves developing web applications, he does development for Android and Windows Mobile in his spare time.

Leave a Reply

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