rustmacro-rules

How to reduce amount of function defining rules inside `macro_rules!`?


I need to create macro rules expanding like this:

define_fn!(fn a());
// expands to
fn a() {}
define_fn!(pub fn a());
// expands to
pub fn a() {}
define_fn!(fn a(arg1: u32,));
// expands to
fn a(arg1: u32) {}
define_fn!(pub fn a(arg1: u32, arg2: i32));
// expands to
pub fn a(arg1: u32, arg2: i32) {}

I could've done this using 4 rules effortlessly, but I want to do this in 1 rule, i.e.

macro_rules! define_fn {
    (<some magic>) => { <some other magic> };
}

How do I do this in 1 rule? Is it even possible?


Solution

  • The little book of Rust macros has a page that shows how to parse a function. Following that page, this should do what you want:

    macro_rules! define_fn {
        ($v:vis fn $name:ident ($($i:ident : $t:ty),*)) => { 
            $v fn $name ($($i: $t),*) {}
        };
    }
    

    Playground