How to make a (simple?) macro

I have this non-working macro that I'd like to make work:

#[macro_export]
macro_rules! xerr {
    ($x:expr) => {{xerror($x)}};
    ($x:expr, $($y:expr),+) => {{xerror(&format!($x, $y))}};
}

The error message is:

error: variable 'y' is still repeating at this depth
  --> src/xerror.rs:13:54
   |
13 |     ($x:expr, $($y:expr),+) => {{xerror(&format!($x, $y))}};

The function's signature is xerror(&str) -> XResult<T> and the use cases are:

return xerr!("some error");
return xerr!("can't read {}: {}", &filename, err);

Weirdly when I try to use it in a differet moduel, this use doesn't work: use crate::xerror::xerr; but this one does: use crate::xerr.

You need to repeat $y the same way it was matched, like: xerror(&format!($x, $($y),+))

2 Likes

Thanks! I'm now using:

#[macro_export]
macro_rules! xerr {
    ($x:expr) => {{return xerror($x);}};
    ($x:expr, $($y:expr),+) => {{return xerror(&format!($x, $($y),+));}};
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.