I would like to write a function that accesses the file and line number of the location in which it gets called.
It would look like this:
fn main() {
prints_calling_location(); // would print `called from line: 2`
prints_calling_location(); // would print `called from line: 3`
}
fn prints_calling_location() {
let caller_line_number = /* ??? */;
println!("called from line: {}", caller_line_number);
}
An alternative to using the "Implicit caller location" (which may not be available/suitable to you for whatever reason) is to do things the C way. I.e. hide your function behind a macro.
playground link
RFC 2091: Implicit caller location adds the
track_caller
feature which enables a function to access the location of its caller.Short answer: to obtain the location in which your function gets called, mark it with
#[track_caller]
and usestd::panic::Location::caller
in its body.Following from that answer, your example would look like this:
playground link
More specifically, the function
std::panic::Location::caller
has two behaviors:#[track_caller]
, it returns a&'static Location<'static>
which you can use to find out the file, line number, and column number in which your function gets called.Within a function that doesn't have
#[track_caller]
, it has the error-prone behavior of returning the actual location where you've invoked it, not where your function gets called, for example:playground link