Capture Stack Frames With runtime.Callers
Walk the call stack with runtime.Callers and runtime.CallersFrames to log function names, files, and line numbers for diagnostics.
Code
package main
import (
"fmt"
"runtime"
)
func inner() {
// skip 2:跳过 runtime.Callers 与 inner 自身
pcs := make([]uintptr, 16)
n := runtime.Callers(2, pcs)
frames := runtime.CallersFrames(pcs[:n])
for {
frame, more := frames.Next()
fmt.Printf("%s %s:%d\n", frame.Function, frame.File, frame.Line)
if !more {
break
}
}
}
func middle() {
inner()
}
func main() {
middle()
fmt.Println("captured frames above")
}What the file does
Capture Stack Frames With runtime.Callers is built around the functions inner, middle and main.
Repetition is confined to for — the rest of the file is straight-line.
Applying it
Entry signature: func inner()
Running the file prints labeled results such as captured frames above — each operation’s effect is visible in the output.
main sequences middle; executing the file runs that flow once.
Statements that matter
func middle() {
inner()
}
func main() {
middle()
fmt.Println("captured frames above")
}
pcs := make([]uintptr, 16)
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does Capture Stack Frames With runtime.Callers print when run?
- The script runs standalone; its 1 labeled outputs include `captured frames above`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.