Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a Rust macro with optional parameters using repetitions?

I'm currently looking into Rust macros and I can not find any detailed documentation on repetitions. I would like to create macros with optional parameters. This would be my idea:

macro_rules! single_opt {
    ($mand_1, $mand_2, $($opt:expr)* ) =>{
        match $opt {
            Some(x) => println!("1. {} 2. {}, 3. {}", $mand_1, $mand_2, x);
            None => single_opt!($mand_1, $mand_2, "Default");
        }
    }
}

fn main() {
    single_opt!(4,4);
}

This example seems to be outdated, since I can not compile it. The Rust book mentions this topic just very briefly. How do I get this example to work?

like image 792
Stein Avatar asked Dec 19 '15 16:12

Stein


People also ask

Can you use macros on Rust?

The most widely used form of macros in Rust is the declarative macro. These are also sometimes referred to as “macros by example,” “ macro_rules! macros,” or just plain “macros.” At their core, declarative macros allow you to write something similar to a Rust match expression.


1 Answers

NOTE: Since this answer was written, Rust has gained the ability to express optional elements in a pattern (stabilized in Rust 1.32.0) using the syntax $(tokens)?.

The first edition of the Rust book has a rather long chapter on macros, but the section on repetitions is a bit shy on examples...

There are several ways to handle optional arguments in macros. If you have an optional argument that can only occur once, then you shouldn't use repetitions: you should instead define multiple patterns in your macro, like this:

macro_rules! single_opt {
    ($mand_1:expr, $mand_2:expr) => {
        single_opt!($mand_1, $mand_2, "Default")
    };
    ($mand_1:expr, $mand_2:expr, $opt:expr) => {
        println!("1. {} 2. {}, 3. {}", $mand_1, $mand_2, $opt)
    };
}

fn main() {
    single_opt!(4, 4);
}

If you want to allow an arbitrary number of arguments, then you need repetition. Your original macro doesn't work because you put the comma outside the repetition, so you'd have to invoke the macro as single_opt!(4,4,);. See How to allow optional trailing commas in macros? for a related case.

If you have a fixed number of arguments followed by a repetition, you can put the comma inside the repetition as the first token:

macro_rules! single_opt {
    ($mand_1:expr, $mand_2:expr $(, $opt:expr)*) => {
        println!("1. {} 2. {}, 3. {}", $mand_1, $mand_2, $($opt),*)
    };
}

However, it doesn't work in this specific case:

error: 3 positional arguments in format string, but there are 2 arguments
 --> src/main.rs:3:22
  |
3 |         println!("1. {} 2. {}, 3. {}", $mand_1, $mand_2, $($opt),*)
  |                      ^^    ^^     ^^
...
8 |     single_opt!(4, 4);
  |     ------------------
  |     |
  |     in this macro invocation
  |     in this macro invocation
  |     in this macro invocation
  |
  = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

So we'll have to go back to defining two patterns:

macro_rules! single_opt {
    ($mand_1:expr, $mand_2:expr) => {
        single_opt!($mand_1, $mand_2, "Default")
    };
    ($mand_1:expr, $mand_2:expr, $($opt:expr),*) => {
        {
            println!("1. {} 2. {}", $mand_1, $mand_2);
            $(
                println!("opt. {}", $opt);
            )*
        }
    };
}

fn main() {
    single_opt!(4, 4, 1, 2);
}

A repetition takes the form $( PATTERN ) SEPARATOR COUNT, where PATTERN is the pattern you want to repeat, SEPARATOR is an optional token that separates each repetition (here, it's ,) and COUNT is either * for "zero or more occurrences" or + for "one or more occurrences".

Then, in the macro expansion, we need a repetition block to be able to access $opt. The syntax is exactly the same, but note that the separator doesn't have to be the same (here, there's no separator in the expansion).

like image 116
Francis Gagné Avatar answered Sep 24 '22 00:09

Francis Gagné