原文标题: Trace caller’s source location in the stable Rust
原文链接: https://blog.knoldus.com/trace-callers-source-location-in-the-stable-rust/
在本文中,我将介绍一种特性用以追踪某个函数的调用位置。我是在某个Rust项目里偶然遇到了这种不得不去追踪函数调用位置的需求。Rust是有这种特性的,但是在stable版本无法使用。所以我实现了一个名为trace_caller的crate并引入trace
这一过程属性宏(procedural attribute macro)用以追踪源码位置。这个crate能够在stable版本的Rust下工作。
这个库底层使用backtrace,因为其在运行时需要backtraces。
如何使用trace_caller:
- 在Cargo.toml里添加依赖
[dependencies]
trace_caller = "0.2.0"
- 在代码里使用
use trace_caller::trace;
#[trace]
fn add(x: u32, y: u32) -> u32 {
x + y
}
fn main() {
let result = add(3, 4);
println!("Result: {}", result);
}
- 运行cargo run
Called from "src/main.rs" at line 9
Result: 7
你可以在这里 https://github.com/ayushmishra2005/trace_caller找到源码。欢迎各位进行pull request。