Expand description
Make a function report the location of its caller instead of its own.
When a function panics, the panic message normally points at the line inside that function
where the panic happened. #[track_caller] changes that: it lets the function see the
Location it was called from, so the panic (and any direct use of Location::caller)
points at the call site instead. The standard library uses this on methods like
Option::unwrap, so a failed unwrap blames the line that called it rather than a line
inside the standard library.
ⓘ
#[track_caller]
fn assert_even(n: i32) {
assert!(n % 2 == 0, "{n} is not even");
}
// The panic blames this line, not the `assert!` inside `assert_even`.
assert_even(3);The attribute applies to functions with the default "Rust" ABI, other than fn main.
For more information, see the Reference on the track_caller attribute.