rust-cookbook icon indicating copy to clipboard operation
rust-cookbook copied to clipboard

Add recipe to building custom format-like macros

Open nyurik opened this issue 2 years ago • 1 comments
trafficstars

There seem to be a lot of "gotchas" when creating a new macro that accepts format arguments. I propose to add a recipe for such cases. Something like this, although my code might also need some improvements. Points of interest:

  • best way to capture format arguments - comma capturing is actually fairly tricky because foo!("{}", bar) can be auto-replaced with foo("{bar}"), which has no commas.
  • proper way to use those captured arguments
#[macro_export]
macro_rules! err_to_io {
    ($error:ident $(, $arg:expr)* $(,)?) => {
        ::std::io::Error::new(
            ::std::io::ErrorKind::Other,
            ::std::format!("{}: {}", ::std::format_args!($($arg,)+), $error))
    };
}

nyurik avatar Nov 27 '22 19:11 nyurik