rust-cookbook
rust-cookbook copied to clipboard
Add recipe to building custom format-like macros
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 withfoo("{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))
};
}