Home > Backend Development > Golang > How Can I Get the Current Function Name in Go Code?

How Can I Get the Current Function Name in Go Code?

Susan Sarandon
Release: 2024-12-15 08:45:14
Original
736 people have browsed it

How Can I Get the Current Function Name in Go Code?

Introspecting Go Code: Retrieving Current Function Name

In Go, obtaining the current function name is crucial for debugging and tracing. FUNCTION macro in gcc provides this functionality, and we aim to emulate it in Go.

Solution

The key lies in the runtime package. Here's a solution:

import (
    "fmt"
    "runtime"
)

func trace() {
    pc := make([]uintptr, 10) // Need at least 1 entry
    runtime.Callers(2, pc)
    f := runtime.FuncForPC(pc[0])
    file, line := f.FileLine(pc[0])
    fmt.Printf("%s:%d %s\n", file, line, f.Name())
}
Copy after login

This function works by:

  1. Obtaining Program Counter (PC): We use runtime.Callers to retrieve the PC of the current function and call stack frames. We specify a depth of 2 to skip the trace function itself.
  2. Retrieving Function Details: Using runtime.FuncForPC, we retrieve the Func object corresponding to the PC. This object provides access to function name, line number, and file name.
  3. Printing Function Info: Finally, we print out the function's file name, line number, and name.

Updated Example

For Go versions 1.7 , the recommended approach is to use runtime.CallersFrames instead of runtime.FuncForPC. An updated example below:

import (
    "fmt"
    "runtime"
)

func trace() {
    pc := make([]uintptr, 10) // Need at least 1 entry
    runtime.CallersFrames(2, pc)
    frame, _ := runtime.CallersFrames(2, pc)
    fmt.Printf("%s:%d %s\n", frame[0].File, frame[0].Line, frame[0].Function)
}
Copy after login

The above is the detailed content of How Can I Get the Current Function Name in Go Code?. 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