Home > Backend Development > Golang > How Can I Get Caller Function Information in Golang?

How Can I Get Caller Function Information in Golang?

Susan Sarandon
Release: 2024-12-26 05:50:32
Original
475 people have browsed it

How Can I Get Caller Function Information in Golang?

Retrieving Caller Function Information in Golang

In Golang, it's possible to obtain insights into the caller function. Consider the following code snippet:

func foo() {
    // Do something
}

func main() {
    foo()
}
Copy after login

The question arises: how can we determine that foo was invoked from main? Other languages, such as C#, facilitate this task using attributes like CallerMemberName.

Thankfully, Golang provides a solution with the runtime.Caller function.

func Caller(skip int) (pc uintptr, file string, line int, ok bool)
Copy after login

Example Implementations

Example #1: Printing Caller File Name and Line Number

package main

import (
    "fmt"
    "runtime"
)

func foo() {
    _, file, no, ok := runtime.Caller(1)
    if ok {
        fmt.Printf("called from %s#%d\n", file, no)
    }
}

func main() {
    foo()
}
Copy after login

Example #2: Retrieving More Information with runtime.FuncForPC

package main

import (
    "fmt"
    "runtime"
)

func foo() {
    pc, _, _, ok := runtime.Caller(1)
    details := runtime.FuncForPC(pc)
    if ok & details != nil {
        fmt.Printf("called from %s\n", details.Name())
    }
}

func main() {
    foo()
}
Copy after login

By utilizing these examples, you can effortlessly gain insights into caller function information in Go.

The above is the detailed content of How Can I Get Caller Function Information in Golang?. 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