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

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

Susan Sarandon
Release: 2024-12-07 09:33:20
Original
915 people have browsed it

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

Retrieving Source Code File Name and Line Number in Go

In programming languages like C/C , developers can leverage FILE and LINE to obtain the current source code file path and line number. Does Go offer a similar functionality?

Answer:

Absolutely. Go provides a built-in function called runtime.Caller to access the source code file name and line number of the current function.

Implementation:

To utilize runtime.Caller, you can call it with an optional integer argument:

func GetSourceInfo(skip int) (string, int) {
    _, thisFile, thisLine, ok := runtime.Caller(skip)
    if !ok {
        return "", 0
    }
    return thisFile, thisLine
}
Copy after login

The skip parameter specifies how many layers up the call stack to ascend. For instance, skip=0 would return the source info for the current function, skip=1 would return the source info for the caller of the current function, and so on.

Example Usage:

import (
    "fmt"
    "runtime"
)

func main() {
    file, line := GetSourceInfo(1)
    fmt.Println("Calling function:", file, line)
}
Copy after login

Output:

Calling function: /path/to/my/file.go 12
Copy after login

The above is the detailed content of How Can I Get the Source Code File Name and Line Number in Go?. 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