rust-lang-nursery / rust-cookbook

https://rust-lang-nursery.github.io/rust-cookbook
Creative Commons Zero v1.0 Universal
2.24k stars 286 forks source link

Add recipe to building custom format-like macros #679

Open nyurik opened 1 year ago

nyurik commented 1 year ago

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:

#[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))
    };
}