Home >Backend Development >Golang >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!