Home >Backend Development >Golang >How Can I Get the Source Code Filename and Line Number in Go?

How Can I Get the Source Code Filename and Line Number in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-12-10 11:26:17475browse

How Can I Get the Source Code Filename and Line Number in Go?

Retrieving Source Code Filename and Line Number in Go

Unlike C/C that utilizes FILE and __LINE__, Go provides a different approach for obtaining the current source code filename and line number.

Solution:

Go offers the runtime.Caller function for this purpose. It can extract the information about the caller function, which includes the source code filename and line number. Here's how you can use it:

import "runtime"

func main() {
    // Get the filename and line number of the caller function
    _, filename, line, _ := runtime.Caller(1)

    // Print the retrieved information
    fmt.Printf("Filename: %s\n", filename)
    fmt.Printf("Line Number: %d\n", line)
}

Extended Functionality:

runtime.Caller can also gather file and line number details for calling functions. For instance, setting its first argument to 2 would provide information about the function that called the current function.

The above is the detailed content of How Can I Get the Source Code Filename and Line Number in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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