Home > Backend Development > Golang > How Can I Get a Go Function's Name at Runtime?

How Can I Get a Go Function's Name at Runtime?

Mary-Kate Olsen
Release: 2024-12-25 14:58:13
Original
130 people have browsed it

How Can I Get a Go Function's Name at Runtime?

How to Retrieve Function Names in Go

It is often desirable to obtain the name of a function in Go during runtime. This can be useful for debugging purposes, logging, or other metaprogramming tasks.

runtime.FuncForPC: A Native Solution

Go provides a built-in function, runtime.FuncForPC, that can retrieve the name of a function given its PC (Program Counter) address. However, it requires reflection to obtain the PC address, which can be cumbersome.

A Simplified Approach

To simplify the process, a straightforward solution using reflect and runtime.FuncForPC can be implemented:

package main

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

func foo() {
}

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

func main() {
    fmt.Println("name:", GetFunctionName(foo))
}
Copy after login

This function accepts a generic interface parameter i and returns the name of the function associated with that interface. In this case, foo is the function whose name is being retrieved.

Example Usage

The following example demonstrates the usage of the GetFunctionName function:

package main

import (
    "fmt"
)

func foo() {
}

func main() {
    fmt.Println("name:", GetFunctionName(foo))
}
Copy after login

When you run this program, it will output:

name: foo
Copy after login

This confirms that the GetFunctionName function successfully retrieves the name of the foo function.

The above is the detailed content of How Can I Get a Go Function's Name at Runtime?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template