macro_rules! impl_trait {
(FromStr<$err:ty> for
$( $(#[$impl_meta:meta])* $type:ident
$([$($decl:tt)+][$($args:tt)+ ])? $(where $($bounded:ident),+ )?
);+
| $s:ident | $expr:expr) => { ... };
(Hash for
$( $(#[$impl_meta:meta])* $type:ident
$([$($decl:tt)+][$($args:tt)+ ])? $(where $($bounded:ident),+ )?
);+
| $self:ident, $state:ident | $expr:expr) => { ... };
(PartialEq for
$( $(#[$impl_meta:meta])* $type:ident
$([$($decl:tt)+][$($args:tt)+ ])? $(where $($bounded:ident),+ )?
);+
| $self:ident, $other:ident | $expr:expr) => { ... };
(fmt::Display+Error for
$( $(#[$impl_meta:meta])* $type:ident
$([$($decl:tt)+][$($args:tt)+ ])? $(where $($bounded:ident),+ )? );+
| $self:ident, $f:ident | $expr:expr) => { ... };
(fmt::$trait:ident for
$( $(#[$impl_meta:meta])* $type:ident
$([$($decl:tt)+][$($args:tt)+ ])? $(where $($bounded:ident),+ )?
);+
| $self:ident, $f:ident | $expr:expr) => { ... };
}Expand description
⌗ 🏗️ A helper macro to concisely implement a few common utility traits.
§Traits supported
- FromStr
- Hash
- PartialEq (where other == &Self)
- fmt:: Debug, Display…
- fmt::Display+Error (common combination)
§Features:
- Allows multiple types in a single invocation, separated by semicolon
- Supports types with or without lifetimes and generics.
- Comma between lifetimes and generics is optional but recommended for clarity.
- Requires the same formatting trait (
fmt::<trait>) to be implemented for all generics.
§Examples
struct S0(usize);
struct S1<T> { v: T }
struct S2<'a, T> { v: &'a T }
struct S3<T: Copy, const N: usize>{ v: [T; N] }
impl_trait![Hash for S0 |self, state| self.0.hash(state)];
// Note: assumes other == &Self
impl_trait![PartialEq for S0 |self, other| self.0 == other.0];
impl_trait![fmt::Binary for S1[T][T] where T |self, f| self.v.fmt(f)];
impl_trait!{fmt::Debug for
S1[T][T] where T;
S2['a, T]['a, T] where T;
S3[T: Copy, const N: usize][T, N] where T |self, f| {
write!(f, "S? {{ v: {:?} }}", self.v)
}}