I'd like to write a macro that allows optional generation of a method body. Specifically, I'm trying to make newtypes easier (for me) to use (so if there's a workaround to solve that problem, that would be helpful as well).
Here's what I've got so far:
macro_rules! alias_basic {
($alias:ident, $t:ty) => {
pub struct $alias($t);
impl Display for $alias {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let $alias(ref v) = *self;
v.fmt(f)
}
}
impl Into<$t> for $alias {
fn into(self) -> $t {
let $alias(v) = self;
v
}
}
impl Deref for $alias {
type Target = $t;
fn deref<'a>(&'a self) -> &'a $t {
let $alias(ref v) = *self;
v
}
}
}
}
macro_rules! alias {
($alias:ident, $t:ty) => {
alias_basic!($alias,$t);
impl From<$t> for $alias {
fn from(v: $t) -> Self {
$alias(v)
}
}
}
}
So far, so good. But what I'd like to do is optionally plug in a TryFrom implementation instead of From, and, if I want a TryFrom, have the macro invocation define the method body.
e.g., I'd want
alias!(Foo,Bar,try_from -> {err -> Quux, body -> /* baz */});