【发布时间】:2018-12-12 14:17:49
【问题描述】:
我正在 Rust 中构建我认为相当简单的宏来接收任意参数列表(str 或 ansi_term::Style 对象)。
我的宏是这样的:
macro_rules! test_macro {
( $( $x: tt ),* ) => (
$(
print!("{} ", $x);
)*
println!();
)
}
对于一个最小的工作示例,我还定义了一个模块和一个函数:
mod foo {
pub fn test() -> &'static str {
"doesn't"
}
}
fn test() -> &'static str {
"doesn't"
}
宏适用于简单的调用,例如
test_macro!("it", "works");
但是如果我尝试更复杂的东西,我会得到编译器错误:
fn test() -> &'static str {
"doesn't"
}
test_macro!("it", test(), "work");
结果
error: no rules expected the token `(`
|
24 | test_macro!("it", test(), "work");
| ^
| |
| help: missing comma here
和
test_macro!("it", foo::test(), "work");
结果
error: no rules expected the token `::`
|
25 | test_macro!("it", foo::test(), "work");
| ^^
这是我第一次使用 Rust 宏,所以我可能会遗漏一些东西。
【问题讨论】:
-
仅供参考:
test_macro!("it", (foo::test()), "work");已被接受。 -
有什么理由不使用
expr而不是tt?