[英]Use local bindings at call site in Rust "macro_rules" macros
考虑以下片段:
macro_rules! quick_hello {
($to_print:expr) => {
{
let h = "hello";
println!("{}", $to_print)
}
}
}
fn main() {
quick_hello!(h);
}
如果我编译它,我得到:
error[E0425]: cannot find value `h` in this scope
--> src/main.rs:12:18
|
12 | quick_hello!(h);
| ^ not found in this scope
但是main
的quick_hello
调用不应该扩展为包含let h = "hello"
语句的块,从而允许我在调用站点将其用作“hello”的速记吗?
我可能会认为这样做是为了保持宏的卫生,但是如果我需要上述行为怎么办? 有没有办法“关闭”卫生来实现这一目标?
为了处理quick_hello
调用, rustc
正在寻找$to_print:expr
的有效表达式。 但是h
在该上下文中不是有效表达式,因此rustc
不会继续执行宏实现并打印错误。
正如上面的人所指出的,目前尚不清楚您希望这个宏做什么。 但是,这会编译并打印 hello:
macro_rules! quick_hello {
(h) => {
let h = "hello";
println!("{}", h)
};
($to_print:expr) => {
{
println!("{}", $to_print)
}
}
}
fn main() {
quick_hello!(h);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.