macro_rules! impl_trait {
(Hash for
$(
$type:ident<$($lt:lifetime),* $(,)? $($generic:ident),*>
$(where $($bounded:ident),+ )?
);+ |$self:ident, $state:ident| $expr:expr) => { ... };
(Hash for $($type:ident),+ |$self:ident, $state:ident| $expr:expr) => { ... };
(fmt::$trait:ident for
$(
$type:ident<$($lt:lifetime),* $(,)? $($generic:ident),*>
$(where $($bounded:ident),+ )?
);+ |$self:ident, $f:ident| $expr:expr) => { ... };
(fmt::$trait:ident for $($type:ident),+ |$self:ident, $f:ident| $expr:expr) => { ... };
}
Expand description
A helper macro to concisely implement a few common utility traits.
§Traits supported
- Hash
- fmt:: Debug, Display…
§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.
§Example
struct S0(usize);
struct S1<T> { v: T }
struct S2<'a, T> { v: &'a T }
impl_trait![Hash for S0 |self, state| self.0.hash(state)];
impl_trait![fmt::Binary for S1<T> where T |self, f| self.v.fmt(f)];
impl_trait!{fmt::Debug for S1<T> where T; S2<'a, T> where T |self, f| {
write!(f, "S? {{ v: {:?} }}", self.v)
}}