Track Caller Location In Helpers
Annotate helper functions with #[track_caller] so Location::caller inside them reports the caller file, line, and column for better diagnostics.
Code
use std::panic::Location;
// #[track_caller] 让 Location::caller() 在函数内部报告"调用方"的位置
#[track_caller]
fn audit(tag: &str) -> String {
let loc = Location::caller();
format!("{tag} at {loc}")
}
fn main() {
// 每个调用点得到自己的 file:line:col,不需要把上下文当参数传进来
println!("{}", audit("entered"));
let report = audit("report");
println!("{report}");
println!("tag roundtrip: {}", audit("again").contains("again"));
}What the code does
The code’s whole job belongs to the functions audit and main.
Points of care
- Nothing arrives from a registry; the language ships every API used.
Applying it
Entry signature: fn audit(tag: &str) -> String
Look for the tag roundtrip: prefixes when the file runs; they tie each line to its step.
The entry point wires audit together — run it once and the whole demo flows.
Statements that matter
fn audit(tag: &str) -> String {
let loc = Location::caller();
format!("{tag} at {loc}")
}
Interactive Tools for This Topic
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Nginx Location Block TesterTest any URL path against Nginx location blocks using authentic Nginx precedence (= exact, ^~ prefix, regex ~ and ~*, and longest prefix) with trace output.
FAQ
- What does Track Caller Location In Helpers print when run?
- Run it as a complete program — the output lines carry labels such as `tag roundtrip:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.