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 }
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)
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!