属性宏比 derive 更强大也更危险:它能改写甚至删除被修饰的条目。这篇写三个最小的属性宏,让编译器展开出来,再验证参数解析、保留原条目、解析错误和用错位置的各种报错。
编译退出码 0 []
运行:
[timed] add 返回了(耗时数量级 微秒以内)
add = 5
[timed] slow 返回了(耗时数量级 毫秒)
slow = done
展开后的 add:
fn add(a: i32, b: i32) -> i32 {
let __t = std::time::Instant::now();
let __r = (|| { a + b })();
{
::std::io::_print(format_args!("[timed] {0} 返回了(耗时数量级 {1})\n",
"add",
if __t.elapsed().as_millis() >= 1 {
"毫秒"
} else { "微秒以内" }));
};
__r
}过程宏的阶段见过程宏的执行阶段。
编译退出码 0
运行:
("GET", "/users", "list_users")
("POST", "/users", "create_user")
原函数仍可调用: users / created error: expected `,`
--> src/main.rs:3:1
|
3 | #[route("GET")] fn a() {}
| ^^^^^^^^^^^^^^^
|
= note: this error originates in the attribute macro `route` (in Nightly builds, run with -Z macro-backtrace for more info)
error: expected string literal
--> src/main.rs:4:9
|
4 | #[route(GET, "/x")] fn b() {}
| ^^^
error: could not compile `app` (bin "app") due to 2 previous errors error[E0425]: cannot find function `gone` in this scope
--> src/main.rs:4:28
|
4 | fn main() { println!("{}", gone()); }
| ^^^^
| error: expected `fn`
--> src/main.rs:3:10
|
3 | #[timed] struct NotFn;
| ^^^^^^
error: could not compile `app` (bin "app") due to 1 previous errorderive 宏的写法见Derive 宏如何生成代码。