有没有办法获取 Rust 中初始化值的位置和文件名?

wye*_*r33 0 rust

有没有办法获取 Rust 中初始化值的位置和文件名?我知道file!line!宏,但它们提供了它们最初被调用的位置的信息,并且我希望从初始化值的位置确定此信息。例如,以下代码不起作用,但与我想要的类似:

// Contains a value as well as where this value was initialized
struct Foo {
    value : usize,
    file : String,
    line : u32,
}
impl Foo {
    fn new(value : usize) -> Foo {
        Foo {
            value,
            file : String::from(std::file!()),
            line : std::line!(),
        }
    }
}

// Test the result
fn main() {
    let foo1 = Foo::new(0);
    println!("foo1 created in file \"{}\" line {}",foo1.file,foo1.line);
    let foo2 = Foo::new(1);
    println!("foo2 created in file \"{}\" line {}",foo2.file,foo2.line);
}
Run Code Online (Sandbox Code Playgroud)

这返回

foo1 created in file "src/main.rs" line 12
foo2 created in file "src/main.rs" line 12
Run Code Online (Sandbox Code Playgroud)

其中不包含值创建的正确行号。我还尝试尽可能透明地执行此操作,以便用户不需要为创建的每个值键入宏。至于为什么,我试图在代码中插入一些调试信息,这对于用户了解代码中的值是在哪里创建的将很有帮助。

api*_*lat 5

您可以通过使用属性标记函数#[track_caller]并使用和宏std::panic::Location::caller()来实现此目的。这最初是为了打印恐慌的位置而设计的,但它似乎并不限于该上下文。file!()line!()

操场