您可以通过调用来查看宏扩展cargo +nightly rustc --profile=check -- -Zunstable-options --pretty=expanded
或使用货物扩展 https://github.com/dtolnay/cargo-expand
fn f1() {
{
::std::io::_print(::std::fmt::Arguments::new_v1(
&["", "\n"],
&match (&(100 / 100),) {
(arg0,) => [::std::fmt::ArgumentV1::new(arg0, ::std::fmt::Debug::fmt)],
},
));
};
();
}
你可以看到最后一个();
本来应该是func_100()
这是因为没有令牌规则generate_func_call
类型的($number: expr)
是。没有匹配扩展的规则。这是因为$number
没有被取代100
正如您在函数中所期望的那样。该宏只是根据以下内容创建更多 Rust 代码片段类型 https://doc.rust-lang.org/reference/macros-by-example.html它接收,它不会尝试评估任何东西。
将代码更改为:
macro_rules! generate_func_call {
($number: expr) => {
match $number {
100 => func_100(),
200 => func_200(),
300 => func_300(),
_ => (),
}
};
}
最后();
更改为:
match 300 {
100 => func_100(),
200 => func_200(),
300 => func_300(),
_ => (),
};
您不必担心额外的跳转语句等,它已被优化为300
是编译时间常数。它只是变成func_300()
.