我试图编写一个生成结构的宏。结构的实现将由宏生成,但是一些代码块将作为宏参数提供。以下是此类宏的最小示例:
macro_rules! make_struct {
($name:ident $block:block) => {
struct $name {
foo: i32,
}
impl $name {
fn new() -> Self {
$name { foo: 42 }
}
fn act (&self) {
$block
}
}
};
}
这是一个如何使用宏的例子:
fn main() {
// Works
make_struct!(Test { println! ("Bar: {:?}", 24); });
let test = Test::new();
test.act();
}
我想在提供的代码中授予对self
的访问权限。类似的东西:
fn main() {
// Does not work
make_struct!(Test { println! ("Foo: {:?}", self.foo); });
let test = Test::new();
test.act();
}
据我所知,由于宏观卫生规则,这不起作用。具体而言,self.foo
表达式在main
函数的语法上下文中进行求值,其中self
不存在。问题是:有没有办法修改宏,以便可以从用户提供的代码访问self
?
答案 0 :(得分:5)
您可以传递闭包而不是块。
make_struct!(Test |this| println!("Foo: {:?}", this.foo));
然后宏可以使用闭包并用self
:
macro_rules! make_struct {
($name:ident $closure:expr) => {
struct $name {
foo: i32,
}
impl $name {
fn new() -> Self {
$name { foo: 42 }
}
fn act (&self) {
let x: &Fn(&Self) = &$closure;
x(self)
}
}
};
}
带有let绑定的舞蹈是必要的,因为闭包中this
的类型无法推断(但是?)。而且,当传递闭包以外的东西时,它还会使宏的错误报告更具可读性。
答案 1 :(得分:3)
通过向宏添加一个参数来找到一种方法,该宏存储将在块中访问self
的名称:
macro_rules! make_struct {
($myname:ident : $type_name:ident $block:block) => {
struct $type_name {
foo: i32,
}
impl $type_name {
fn new() -> Self {
$type_name { foo: 42 }
}
fn act (&self) {
let $myname = self;
$block
}
}
};
}
fn main() {
make_struct!(myself: Test { println! ("Foo: {:?}", myself.foo); });
let test = Test::new();
test.act();
}