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

Interview Questions

Soon You will get CSS, JavaScript, React Js, and TypeScript So Subscribe to it.

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.

Related Posts