在另一个宏中写入宏是可能的.例如,假设我定义了以下两个宏:
macro_rules! myprint(
($a:expr) => (print!("{}", $a))
)
macro_rules! myprintln(
($a:expr) => (println!("{}", $a))
)
由于这两个宏重复了很多代码,我可能想编写一个宏来生成这些宏.
我试着创造这样一个meta macro.
#![feature(macro_rules)]
macro_rules! metamacro(
($i:ident) => (
macro_rules! $i (
($a:expr) => ({println!("hello {}", $a)})
)
);
)
metamacro!(foo)
fn main() {
foo!(1i);
}
但会出现以下错误:
<anon>:6:13: 6:14 error: unknown macro variable `a`
<anon>:6 ($a:expr) => ({println!("hello {}", $a)})
^
playpen: application terminated with error code 101
Program ended.
Edit:在反复使用宏之后,我发现如果返回的宏没有收到任何参数,则高阶宏的工作原理与预期相同.例如,下面的code
#![feature(macro_rules)]
macro_rules! metamacro(
($i:ident) => (
macro_rules! $i (
() => ({println!("hello")})
)
);
)
metamacro!(foo)
fn main() {
foo!();
}
打印hello
张