Help about writing macros

How can I write a macro like this:

#[macro_export]
macro_rules! unwrap_continue {
    ($e:expr, $($arg:tt)*,) => {
        match $e {
            Ok(r) => r,
            Err(e) => {
                println!("{:?} {}", e, $($args:tt)*);
                continue;
            }
        }
    }
}

so that this line:

unwrap_continue!(e, info1, info2);

do the same thing as this block:

match e {
    Ok(r) => r,
    Err(e) => {
       println!("{:?} {:?} {:?}", e, info1, info2);
       continue; 
    }
}
macro_rules! unwrap_continue {
    ($e:expr, $($args:expr),* $(,)*) => {
        match $e {
            Ok(r) => r,
            Err(e) => {
                println!(
                    concat!("{:?}", $(unwrap_continue!(@replace $args => " {:?}")),*),
                    e,
                    $($args,)*
                );
                continue;
            }
        }
    };
    
    (@replace $_discard:tt => $($tts:tt)*) => {
        $($tts)*
    };
}
3 Likes

That's cool use of internal rules if anyone else was wondering what's with the @ there:
https://veykril.github.io/tlborm/decl-macros/patterns/internal-rules.html

2 Likes

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.