How to print function name in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

Today, I’m going to show you how we get the function name in golang, here we will use "reflect" and "runtime" packages to get the function.

We have created a function that returns the function name of the passed-in parameter.

func GetFunctionName(i interface{}) string {
    return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
}

Let’s write a sample function and pass it in and then check what’s returning.

package main

import (
    "fmt"
    "reflect"
    "runtime"
)

func sampleFunction() {
}

func GetFunctionName(i interface{}) string {
    return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
}

func main() {
    // This will print "name: main.sampleFunction"
    fmt.Println("name:", GetFunctionName(sampleFunction))
}

It’s returning "name: main.sampleFunction" in golang console.

print, function name, golang

Try it yourself

All the best 👍

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

I'm working on some more Cheat Sheets book on Jquery, TypeScript, React js and for other languages. I will send it once it's completed.

Stay tuned working on React Js Cheat Sheets Book

Related Posts