rust - Access to self from the parameters of a macro that creates a struct -
i'm trying write macro generates struct. implementation struct generated macro, blocks of code provided macro arguments. here minimal example of such macro:
macro_rules! make_struct { ($name:ident $block:block) => { struct $name { foo: i32, } impl $name { fn new() -> self { $name { foo: 42 } } fn act (&self) { $block } } }; }
and here example of how macro can used:
fn main() { // works make_struct!(test { println! ("bar: {:?}", 24); }); let test = test::new(); test.act(); }
i give access self
inside supplied code. like:
fn main() { // not work make_struct!(test { println! ("foo: {:?}", self.foo); }); let test = test::new(); test.act(); }
i understand not work because of macro hygiene rules. specifically, self.foo
expression evaluated in syntax context of main
function, self
not exist. question is: there way modify macro self
may accessed user-supplied code?
you can pass closure instead of block.
make_struct!(test |this| println!("foo: {:?}", this.foo));
then macro can use closure , call 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) } } }; }
the dance let binding necessary, because type of this
in closure can't inferred (yet?). , makes macro's error reporting little more readable when other closure passed.
Comments
Post a Comment