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.

RustResilience

Code

rustsnippet
16 lines
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

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:`.