Else, in declarative macros

Is there a way of handling a $($t:tt)? And printing something only if it is not provided?


$($t)?or_else("Nothing Provided")


I can work around it with multiple clauses, but it would save an explosion of options if for each mode I could do this directly

You’re a bit too unspecific with your example for me to actually understand how you get an “explosion of options” from using multiple clauses, how bad it is (or what this phrasing even means) but “working around it” is a reoccurring theme around declarative macros.

My best guess as to what “explosion” you might think of and how to mitigate it:

macro_rules! foo{
    (option1:, option2: $($t:tt)?, option3: $($u:tt)?) => {
        foo!{option1: "default 1", option2: $($t)?, option3: $($u)?}
    (option1: $s:tt, option2:, option3: $($u:tt)?) => {
        foo!{option1: $s, option2: "default 2", option3: $($u)?}
    (option1: $s:tt, option2: $t:tt, option3:) => {
        foo!{option1: $s, option2: $t, option3: "default 3"}
    (option1: $s:tt, option2: $t:tt, option3: $u:tt) => {
        ($s, $t, $u)

fn main() {
    println!("{:?}", foo!(option1:, option2: "custom 2", option3:));

Thanks, I think that mitigates the explosion I was referring to.

I'd still prefer to use an else if that were at all possible. Then I could do that in one clause.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.