Home > Backend Development > Golang > How Does Go Access Source File Information Like C/C 's __FILE__ and __LINE__ Macros?

How Does Go Access Source File Information Like C/C 's __FILE__ and __LINE__ Macros?

Susan Sarandon
Release: 2024-12-04 11:28:10
Original
281 people have browsed it

How Does Go Access Source File Information Like C/C  's __FILE__ and __LINE__ Macros?

Accessing Source File Information in Go

In languages like C/C , the __FILE__ and __LINE__ macros provide easy access to the current file and line number. Does Go offer a similar mechanism?

Answer:

Yes, Go provides the runtime.Caller function for this purpose. It returns a slice of uintptr variables pointing to caller frames in the call stack. The fmt.Sprintf function can then be used to extract the source file name and line number information from the frames.

import (
    "fmt"
    "runtime"
)

func main() {
    // Get the caller function information
    frames := runtime.Callers(1, 2)

    // Extract the source file name and line number
    fileName, line := getFileInfo(frames[0])
    fmt.Printf("Source file: %s, Line number: %d", fileName, line)
}

// Function to extract file name and line number from caller frame
func getFileInfo(f uintptr) (string, int) {
    // Extract the file name
    frame := runtime.Frame(f)
    return frame.File, frame.Line
}
Copy after login

Additionally, runtime.Caller can also provide the source file information for calling functions:

// Get the caller function information
frames := runtime.Callers(2, 3) // Skip the main function and runtime.Callers

// Extract the source file name and line number
fileName, line := getFileInfo(frames[0])
fmt.Printf("Source file: %s, Line number: %d", fileName, line)
Copy after login

The above is the detailed content of How Does Go Access Source File Information Like C/C 's __FILE__ and __LINE__ Macros?. 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