How to name an arbitrary sequence of things in a macro?

I am trying to use ?in a macro matching an arbitrary keyword:

#![feature(macro_at_most_once_rep)]

macro_rules! foo {
    (
        pub fn $name:ident (
            & $m : $( mut )? self
        )
    ) => (
        pub fn $name (
            & $m self
        ) {}
    )
}

struct Foo;

impl Foo {
    foo!( pub fn bar(&mut self) );
    foo!( pub fn baz(&self) );
}

fn main() {}

I tried a variety of syntax, but they all failed. How to do it?

+6
source share
1 answer

One trick is to insert a repeat with a dummy marker.

#![feature(macro_at_most_once_rep)]

macro_rules! foo {
    (
        pub fn $name:ident (
            & $( $(@$m:tt)* mut )? self
        )
    ) => (
        pub fn $name (
            & $( $(@$m)* mut )? self
        ) {}
    )
}

struct Foo;

impl Foo {
    foo!( pub fn bar(&mut self) );
    foo!( pub fn baz(&self) );
}

fn main() {
    (&mut Foo).bar();
    (&mut Foo).baz();
    // (&Foo).bar(); //~ERROR cannot borrow
    (&Foo).baz();
}
+1
source

All Articles